# Payment Methods Controller Documentation

**File**: `/controllers/paymentMethodsController.php`  
**Purpose**: Manages payment methods configuration and settings for the ERP system  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: ~208

---

## 📋 Overview

The Payment Methods Controller handles the complete lifecycle management of payment methods in the ERP system. It provides functionality for creating, viewing, editing, and managing different payment methods that can be used throughout the system for processing transactions.

### Primary Functions
- [x] Create new payment methods with multilingual support
- [x] View/list all active payment methods
- [x] Edit existing payment method details
- [x] Soft delete payment methods (mark as deleted)
- [x] Image upload for payment method branding
- [x] API integration support (API keys, merchant IDs)
- [x] Active/inactive status management
- [x] AJAX and cURL support for API operations
- [x] Multilingual content (Arabic/English)

### Related Controllers
- [payedController.php](payedController.md) - Payment status display
- [clientPayedDeptController.php](#) - Customer payment processing
- [sellbillController.php](#) - Sales with payment methods
- [buyBillController.php](#) - Purchase payments

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **paymentmethods** | Payment method definitions | id, name_ar, name_en, image, note_ar, note_en, is_active, apikey, merchant_id, is_del, user_id, userdel_id, sys_date |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial/help videos | youtubelinkid, title, url |
| **user** | System users | userid, username |

### Table Structure Details
**paymentmethods**:
- `id` - Primary key, auto-increment
- `name_ar` - Arabic payment method name
- `name_en` - English payment method name  
- `image` - Payment method logo/icon file path
- `note_ar` - Arabic description/notes
- `note_en` - English description/notes
- `is_active` - Status flag (1=active, 0=inactive)
- `apikey` - API key for payment gateway integration
- `merchant_id` - Merchant identifier for payment processing
- `is_del` - Soft delete flag (0=active, 1=deleted)
- `user_id` - User who created the record
- `userdel_id` - User who deleted the record
- `sys_date` - Creation timestamp

---

## 🔑 Key Functions

### 1. **Default Action** - Add Payment Method Form
**Location**: Lines 55-57  
**Purpose**: Display form for creating new payment methods

**Process Flow**:
1. Load payment method creation form
2. Display via `paymentMethodsView/add.html` template
3. Form includes fields for multilingual names, descriptions, images, and settings

---

### 2. **add()** - Create New Payment Method
**Location**: Lines 152-172  
**Purpose**: Process new payment method creation with image upload

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

**Input Parameters**:
- `$_POST['name_ar']` - Arabic name
- `$_POST['name_en']` - English name
- `$_POST['note_ar']` - Arabic description
- `$_POST['note_en']` - English description
- `$_POST['is_active']` - Active status (0/1)
- `$_FILES['image']` - Payment method logo

**Process Flow**:
1. Extract POST data for payment method details
2. Upload image file via `uploadnew()` function
3. Create new RedBeanPHP record
4. Set all properties including timestamp and user ID
5. Save to database with soft delete flag set to 0
6. Return new payment method ID

**Image Handling**:
```php
$image = uploadnew('image', False, 0, 0, 'paymentmethods');
```

**Data Assignment**:
```php
$rdispense = R::dispense('paymentmethods');
$rdispense->name_ar = $name_ar;
$rdispense->name_en = $name_en;
$rdispense->image = $image;
$rdispense->sys_date = date("Y-m-d H:i:s");
$rdispense->user_id = $_SESSION['userid'];
$rdispense->is_del = 0;
```

---

### 3. **show()** - List Payment Methods
**Location**: Lines 76-84  
**Purpose**: Display list of all active payment methods

**Process Flow**:
1. Query all payment methods where `isdel = 0`
2. Load YouTube tutorial links
3. Assign data to Smarty template
4. Display via `paymentMethodsView/show.html`
5. Enable custom validation

**Query Details**:
```php
$showData = R::findAll('paymentmethods', 'isdel = 0');
```

**Template Variables**:
- `$showData` - Array of active payment methods
- `$youtubes` - Tutorial video links
- `$customCheck` - Enable custom functionality

---

### 4. **edit()** - Edit Payment Method Form
**Location**: Lines 104-109  
**Purpose**: Load existing payment method data for editing

**Function Signature**:
```php
// Triggered by: do=edit&id=X
$id = $_GET['id'];
```

**Process Flow**:
1. Get payment method ID from URL parameter
2. Load existing record from database
3. Assign data to Smarty template
4. Display edit form via `paymentMethodsView/edit.html`

---

### 5. **update()** - Update Payment Method
**Location**: Lines 174-196  
**Purpose**: Process payment method updates with image handling

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

**Input Parameters**:
- `$_POST['id']` - Payment method ID to update
- Various POST fields for updated data
- `$_FILES['image']` - New image (optional)

**Process Flow**:
1. Extract POST data including ID
2. Handle image upload/update via `uploadupdate()`
3. Load existing record from database
4. Update all modified fields
5. Preserve existing API credentials if not provided
6. Save updated record

**API Field Handling**:
```php
$rupdate->apikey = empty($_POST['apikey']) ? $rupdate->apikey : $_POST['apikey'];
$rupdate->merchant_id = empty($_POST['merchant_id']) ? $rupdate->merchant_id : $_POST['merchant_id'];
```

**Bug Alert**: Variable mismatch between POST extraction and assignment
```php
// BUG: Variables are extracted as 'title', 'content' etc. 
// but assigned as 'name_ar', 'note_ar' etc.
$title = $_POST['title'];           // Should be 'name_ar'
$content = $_POST['content'];       // Should be 'note_ar'
$rupdate->name_ar = $name_ar;       // Undefined variable!
```

---

### 6. **deleteFinaly()** - Soft Delete Payment Method
**Location**: Lines 198-207  
**Purpose**: Mark payment method as deleted without physical removal

**Function Signature**:
```php
function deleteFinaly($id)
```

**Process Flow**:
1. Load payment method record by ID
2. Set `is_del = 1` (soft delete)
3. Record deletion user ID
4. Save updated record
5. Image files are preserved (deletion commented out)

**Soft Delete Implementation**:
```php
$rtrash = R::load('paymentmethods', $id);
$rtrash->is_del = 1;
$rtrash->userdel_id = $_SESSION['userid'];
R::store($rtrash);
```

---

## 🔄 Workflows

### Workflow 1: Create New Payment Method
```
┌─────────────────────────────────────────────────────────────┐
│               START: Create Payment Method                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Creation Form                                   │
│     - Load paymentMethodsView/add.html                     │
│     - Include fields for names, descriptions, image        │
│     - Include API integration fields                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission (do=add)                       │
│     - Extract POST data                                     │
│     - Validate required fields                             │
│     - Handle image upload                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Database Record                                  │
│     - Create RedBeanPHP dispensed object                   │
│     - Set all properties including metadata                │
│     - Store in paymentmethods table                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Handle Response                                         │
│     - Return JSON for AJAX requests                        │
│     - Redirect to success page for regular requests        │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Edit Existing Payment Method
```
┌─────────────────────────────────────────────────────────────┐
│              START: Edit Payment Method                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Edit Form (do=edit&id=X)                          │
│     - Get payment method ID from URL                       │
│     - Load existing data from database                     │
│     - Populate form with current values                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Update (do=update)                             │
│     - Extract updated data from POST                       │
│     - Handle image update if provided                      │
│     - Preserve existing API keys if not changed            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Database Record                                  │
│     - Load existing record by ID                           │
│     - Update modified fields                               │
│     - Maintain audit trail                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Return Success Response                                 │
│     - JSON response for AJAX                               │
│     - Redirect for standard requests                       │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description | AJAX Support |
|---------------|----------------|-------------|--------------|
| `do=` (empty) | Default | Display add form | No |
| `do=add` | `add()` | Create new payment method | Yes |
| `do=show` | `show()` | List all payment methods | No |
| `do=edit` | `edit()` | Display edit form | No |
| `do=update` | `update()` | Update existing method | Yes |
| `do=deleteFinaly` | `deleteFinaly()` | Soft delete method | Yes |
| `do=sucess` | - | Success confirmation page | No |
| `do=error` | - | Error display page | No |

### Required Parameters by Action

**Create Payment Method** (`do=add`):
- `name_ar` - Arabic name (required)
- `name_en` - English name (required)
- `note_ar` - Arabic description
- `note_en` - English description
- `is_active` - Status flag (0/1)
- `image` - Logo file (optional)

**Edit Payment Method** (`do=edit`):
- `id` - Payment method ID (URL parameter)

**Update Payment Method** (`do=update`):
- `id` - Payment method ID
- Updated field values
- `apikey` - Payment gateway API key
- `merchant_id` - Merchant identifier

**Delete Payment Method** (`do=deleteFinaly`):
- `id` - Payment method ID (URL parameter)

---

## 🧮 Calculation Methods

**No financial calculations performed** - This controller focuses on configuration management rather than payment processing calculations.

**Image Processing**:
```php
// Upload new image
$image = uploadnew('image', False, 0, 0, 'paymentmethods');

// Update existing image
$image = uploadupdate('image', 'imageurl', False, 0, 0, 'paymentmethods');
```

---

## 🔒 Security & Permissions

### Authentication & Session Management
```php
session_start();
ob_start();
// User ID validation
$_SESSION['userid']
```

**Security Features**:
- Session-based authentication required for all operations
- User tracking for creation and deletion activities
- Input parameter casting for integers: `(int) $_POST['is_active']`
- File upload security via `uploadnew()` function
- Soft delete preserves data integrity

### Input Validation & Sanitization
- POST data extraction without explicit sanitization
- Integer casting for critical fields
- File upload validation handled by upload functions
- No direct SQL queries (using RedBeanPHP ORM)

### Permission Model
- No explicit permission checking beyond authentication
- Operations tracked by user ID
- Deletion requires valid session

**Security Concerns**:
1. No input sanitization for text fields
2. No explicit permission level checking
3. File upload validation depends on upload function implementation

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   - `paymentmethods(is_del, is_active)` - For active method queries
   - `paymentmethods(user_id)` - For user-based filtering

2. **Query Patterns**:
   - Simple `R::findAll()` queries for listing
   - Single record loads by ID for editing
   - RedBeanPHP ORM provides automatic optimization

### File Storage
- Image files stored in `/upload/paymentmethods/` directory
- No automatic cleanup on deletion (images preserved)
- Upload function handles file validation and naming

### Memory Usage
- Minimal data structures (single records or small lists)
- Template-based rendering reduces memory overhead

---

## 🐛 Common Issues & Troubleshooting

### 1. **Variable Mismatch in update() Function**
**Issue**: Undefined variables causing update failures  
**Cause**: POST field names don't match variable assignments

**Bug Location** (Lines 176-186):
```php
// WRONG: Extract with wrong names
$title = $_POST['title'];      // Should be 'name_ar'
$content = $_POST['content'];   // Should be 'note_ar'

// BROKEN: Assign undefined variables
$rupdate->name_ar = $name_ar;   // $name_ar is undefined!
```

**Fix**:
```php
// CORRECT: Match POST fields to assignments
$name_ar = $_POST['name_ar'];
$name_en = $_POST['name_en'];
$note_ar = $_POST['note_ar'];
$note_en = $_POST['note_en'];
$is_active = (int) $_POST['is_active'];
```

### 2. **Image Upload Failures**
**Issue**: Image not uploading or updating correctly  
**Debug**:
```php
// Check upload function status
$image = uploadnew('image', False, 0, 0, 'paymentmethods');
if (empty($image)) {
    echo "Upload failed";
}

// Verify directory permissions
chmod('/path/to/upload/paymentmethods/', 0755);
```

### 3. **AJAX Response Issues**
**Issue**: AJAX calls not returning proper JSON  
**Fix**:
```php
// Ensure proper JSON headers
header('Content-Type: application/json');
echo json_encode($data);
exit; // Prevent additional output
```

### 4. **Soft Delete Not Working**
**Issue**: Deleted payment methods still appearing  
**Debug**:
```sql
-- Check soft delete status
SELECT id, name_en, is_del, userdel_id FROM paymentmethods;

-- Verify query filter
SELECT * FROM paymentmethods WHERE is_del = 0;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Create Payment Method
```
1. Navigate to /controllers/paymentMethodsController.php
2. Fill in Arabic and English names
3. Upload payment method logo
4. Set active status
5. Submit form
6. Verify record created in database
7. Check image uploaded to correct directory
```

### Test Case 2: Edit Payment Method
```
1. Go to payment methods list (do=show)
2. Click edit on existing method
3. Modify name and description
4. Upload new image
5. Add API credentials
6. Submit update
7. Verify changes saved correctly
```

### Test Case 3: AJAX Operations
```
1. Set curlpost=1 in POST data
2. Submit add/update/delete requests
3. Verify JSON responses
4. Check status codes and messages
```

### Test Case 4: Soft Delete
```
1. Delete payment method via deleteFinaly
2. Verify is_del flag set to 1
3. Confirm record not visible in show list
4. Check userdel_id populated correctly
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [Upload Functions Documentation](#) - File upload system
- [RedBeanPHP ORM Guide](#) - Database operations
- [Smarty Template System](#) - Template documentation
- [payedController.md](payedController.md) - Payment status display

---

**Documented By**: AI Assistant  
**Review Status**: ⚠️ Contains bugs in update() function  
**Next Review**: After bug fixes implemented