# Client Paid Debt Controller Documentation

**File**: `/controllers/clientPayedDeptController.php`  
**Purpose**: Manages customer payment processing, debt collection, and cash flow integration for customer accounts  
**Last Updated**: December 20, 2024  
**Total Functions**: 12  
**Lines of Code**: ~2,402

---

## 📋 Overview

The Client Paid Debt Controller is a comprehensive payment processing module that handles customer debt collection, cash management, and accounting integration. It manages the complete payment lifecycle from collection to accounting entries. The controller provides:
- Customer payment collection interface
- Multiple payment method support
- Cash register/safe integration
- Automatic accounting entry generation
- Payment history tracking
- Multi-currency support
- Tag-based payment categorization
- AJAX-powered payment processing
- Receipt generation and management

### Primary Functions
- [x] Customer payment collection
- [x] Cash register/safe management
- [x] Multi-currency payment processing
- [x] Automatic accounting entries generation
- [x] Payment history and reporting
- [x] Tag-based payment categorization
- [x] Receipt printing integration
- [x] Payment editing and deletion
- [x] Daily cash flow tracking
- [x] Supplier payment integration
- [x] Employee commission tracking
- [x] AJAX data processing for reports

### Related Controllers
- [clientController.php](clientControllerNew.md) - Customer management
- [clientdebt.php](clientdebt.md) - Customer debt tracking
- [clientReportsController.php](clientReportsController.md) - Customer reports
- [saveController.php](#) - Cash register management
- [savedailyController.php](#) - Daily cash operations
- [sellbillController.php](sellbillController.md) - Sales integration

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **clientdebtchange** | Customer debt transactions | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, paySerialNo, tablename, tagids |
| **client** | Customer master data | clientid, clientname, clientdebt, clientphone, clientmobile, conditions |
| **savedaily** | Daily cash operations | savedailyid, saveid, savedailychangeamount, savedailychangetype, tablename, savedailymodelid |
| **save** | Cash registers/safes | saveid, savename, savevalue, saveConversionFactor |

### Accounting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **dailyentry** | Journal entries | dailyentryid, dailyentryserial, dailyentrydate, dailyentrytotalamount, dailyentrydescription |
| **dailyentrycreditor** | Credit side entries | dailyentrycreditorid, dailyentryid, accountstreeid, dailyentrycreditoramount |
| **dailyentrydebtor** | Debit side entries | dailyentrydebtoryid, dailyentryid, accountstreeid, dailyentrydebtorramount |
| **accountstree** | Chart of accounts | accountstreeid, accountstreecode, accountstreename, accountstreetype |

### Integration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **supplier** | Supplier information | supplierid, suppliername |
| **supplierdebtchange** | Supplier debt tracking | supplierdebtchangeid, supplierid, supplierdebtchangeamount, supplierdebtchangedate |
| **premium** | Employee commissions | premiumid, employeeid, premiumamount, premiumdate |
| **associatedtags** | Payment categorization | associatedtagid, associatedtagname, conditions |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **currency** | Multi-currency support | currencyid, currencyname, currencyrate |
| **user** | System users | userid, username, viewclients, viewbills |
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **Default Action** - Payment Collection Form
**Location**: Line 198-246  
**Purpose**: Display customer payment collection interface with payment options

**Process Flow**:
1. Check user authentication
2. Load payment serial number (auto-increment)
3. Load available cash registers/safes
4. Load customer list (filtered by user permissions)
5. Load currency options
6. Load available payment tags
7. Display payment form template

**Key Features**:
- Auto-generated payment serial numbers
- Cash register selection
- Multi-currency support
- Customer dropdown with permission filtering
- Tag-based categorization

---

### 2. **add()** - Process Customer Payment
**Location**: Line 729-1159  
**Purpose**: Process customer payment with full accounting integration

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

**Input Processing**:
```php
$clientid = (int) $_POST['clientid'];
$clientdebtchangeamount = (float) $_POST['clientdebtchangeamount'];
$paymethod = $_POST['paymethod']; // Collection method
$saveid = (int) $_POST['saveid']; // Cash register ID
$paySerialNo = (int) $_POST['paySerialNo']; // Payment serial
$currency = (int) $_POST['currency']; // Currency selection
$tagids = $_POST['tagids']; // Associated tags
```

**Process Flow**:
1. **Validation**:
   - Validate customer ID and payment amount
   - Check currency rates and conversion
   - Verify cash register availability
   
2. **Payment Record Creation**:
   - Create debt change record (type 1 = payment)
   - Set payment method and description
   - Link associated tags
   
3. **Cash Register Integration**:
   - Update cash register balance
   - Create daily cash operation record
   - Handle currency conversion if applicable
   
4. **Accounting Integration**:
   - Generate journal entry
   - Debit: Cash/Bank account
   - Credit: Customer account
   - Create creditor and debtor records
   
5. **Customer Balance Update**:
   - Decrease customer debt balance
   - Update client record
   
6. **Special Integrations**:
   - Handle supplier payment linkage (if applicable)
   - Process employee commissions
   - Generate receipt number

**Accounting Entry Structure**:
```php
// Journal Entry
$dailyEntry->dailyentryserial = generateDailyEntrySerial();
$dailyEntry->dailyentrydate = $today;
$dailyEntry->dailyentrytotalamount = $paymentAmount;
$dailyEntry->dailyentrydescription = "تحصيل من العميل: " . $customerName;

// Debit: Cash Account
$dailyEntryDebtor->accountstreeid = getCashAccountId($saveid);
$dailyEntryDebtor->dailyentrydebtorramount = $paymentAmount;

// Credit: Customer Account
$dailyEntryCreditor->accountstreeid = getCustomerAccountId($clientid);
$dailyEntryCreditor->dailyentrycreditoramount = $paymentAmount;
```

---

### 3. **show()** - Payment History Report
**Location**: Line 1377-1392  
**Purpose**: Display payment transactions within date range with totals

**Function Signature**:
```php
function show($startDate, $endDate)
```

**Process Flow**:
1. Query payment transactions by date range
2. Calculate total payments collected
3. Assign data to template for display
4. Support pagination for large datasets

**Features**:
- Date range filtering
- Payment amount totals
- Pagination support
- Detailed transaction listing

---

### 4. **edit()** - Payment Modification
**Location**: Line 1411-1431  
**Purpose**: Load payment data for editing and display modification form

**Function Signature**:
```php
function edit($clientdebtchangeid)
```

**Process Flow**:
1. Load payment transaction details
2. Retrieve associated cash register information
3. Load associated tags for the payment
4. Pre-populate edit form
5. Handle payment modification submission

**Data Loading**:
```php
$paymentData = $clientDeptChangeDAO->load($clientdebtchangeid);
$saveId = R::getCell('SELECT saveid FROM savedaily WHERE tablename = "clientPayedDeptController.php" AND savedailymodelid = ' . $clientdebtchangeid);
$paymentData->savename = R::getCell('SELECT savename FROM save WHERE saveid = ' . $saveId);
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientController.php](clientControllerNew.md) - Customer management
- [clientdebt.php](clientdebt.md) - Customer debt tracking
- [saveController.php](#) - Cash register management
- [dailyentry.php](#) - Accounting system

---

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