# Bills Functions Controller Documentation

**File**: `/controllers/billsfunctions.php`  
**Purpose**: Core billing system utilities for optical sales operations with payment processing  
**Last Updated**: December 20, 2024  
**Total Functions**: 25+  
**Lines of Code**: ~1,978

---

## 📋 Overview

The Bills Functions Controller is the core utility library for the ERP's optical billing system. It provides comprehensive functionality for:
- Sales bill processing and management
- Multi-payment method handling (cash, insurance, card)
- Product inventory management
- Client debt tracking and accounting
- Daily entry and financial reporting
- Medical prescription (kashf) handling
- Product pricing and costing
- Store operation management
- Offline bill synchronization
- Complex payment calculations

### Primary Functions
- [x] Sales bill creation and management
- [x] Multi-payment processing (cash/insurance/card)
- [x] Inventory management and tracking
- [x] Client debt management
- [x] Medical prescription integration
- [x] Financial accounting entries
- [x] Offline/online bill synchronization
- [x] Product pricing and costing
- [x] Store operations management
- [x] Payment network integration

### Related Controllers
- [sellbillController.php](sellbillController.md) - Sales bill operations
- [buyBillController.php](buyBillController.md) - Purchase operations
- [billsfunctionsbuy.php](billsfunctionsbuy.md) - Purchase utilities

---

## 🗄️ Database Tables

### Primary Bill Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **bills** | Sales bill master | billid, clientid, billno, finalnetbillvalue, waitvalue, kashfid, dailyentryid |
| **billsproducts** | Bill line items | id, billid, productid, productno, productprice, producttotalprice, storeid |
| **doctorkashf** | Eye examination records | id, customerid, kashfid, doctorid, date, sphere/cylinder/axis values |
| **kashf** | Medical examination master | id, customerid, kashfvalue, kashftype, doctorid, paystatus |

### Financial Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **clientdebtchange** | Customer debt tracking | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype, tablename |
| **dailyentry** | Accounting journal entries | dailyentryid, dDateTime, entryComment, fromFlag |
| **dailyentrycreditor** | Credit entries | id, dailyentryid, accountstreeid, value, pluginControllerName |
| **dailyentrydebtor** | Debit entries | id, dailyentryid, accountstreeid, value, pluginControllerName |
| **storereport** | Inventory movement log | storereportid, productid, storeid, productbefore, productafter, tablename |

### Master Data Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer master | clientid, clientname, clientdebt, clientarea, treeId |
| **product** | Product catalog | productid, productName, productBuyPrice, lastbuyprice, meanbuyprice |
| **storedetail** | Current inventory | storedetailid, productid, storeid, productquantity |
| **save** | Cash registers | saveid, savename, savecurrentvalue, treeId |
| **insurancecompanies** | Insurance providers | id, name, discountpercent |
| **paymentnetworks** | Payment networks | id, name, discountpercent |

---

## 🔑 Key Functions

### 1. **add()** - Complete Bill Processing
**Location**: Line 247  
**Purpose**: Main function for creating optical sales bills with full payment processing

**Function Signature**:
```php
function add($offline) // $offline: 0=online, 1=offline
// Returns: [flag, billId, detailResult]
```

**Process Flow**:
1. Save bill details via `saveBillDetails()`
2. Save bill products via `saveBillProducts()`
3. Handle offline/online processing differences
4. Return processing results and bill ID

**Features**:
- Supports both online and offline bill creation
- Handles multiple payment methods
- Integrates medical examination data
- Manages inventory updates
- Creates accounting entries

---

### 2. **saveBillDetails()** - Bill Master Record Creation
**Location**: Line 258  
**Purpose**: Create main bill record with payment processing and client debt management

**Function Signature**:
```php
function saveBillDetails($offline)
// Returns: Array with flag, note, billId
```

**Complex Processing Logic**:
1. **Parameter Extraction**: Extract and validate all POST parameters
2. **Offline Bill Handling**: Generate bill numbers, handle new clients
3. **Online Bill Handling**: Validate bill numbers, check duplicates
4. **Medical Examination**: Process internal/external kashf (eye exams)
5. **Payment Processing**: Handle cash, insurance, card payments
6. **Client Debt**: Update customer debt balances
7. **Daily Entry**: Create accounting journal entries

**Payment Types Supported**:
```php
// Payment method processing
$paymentamethods = $_POST['paymentamethods'];
foreach ($paymentamethods as $method) {
    switch($method) {
        case 'insurance': saveInsurancePayment(); break;
        case 'card': saveCardPayment(); break;
        case 'cash': saveCashPayment(); break;
    }
}
```

---

### 3. **saveInternalKashf()** - Medical Examination Processing
**Location**: Line 434  
**Purpose**: Handle internal eye examination (kashf) records

**Function Signature**:
```php
function saveInternalKashf($clientId, $offline)
// Returns: Doctor kashf ID
```

**Process Flow**:
1. Check if offline kashf already exists
2. Create kashf master record if needed
3. Create doctor kashf detail record
4. Mark kashf as used to prevent duplicate discounts
5. Update kashf payment status

**Medical Data Handling**:
```php
// Left and right eye measurements
$D_Lsphere = filter_input(INPUT_POST, 'D_Lsphere');  // Distance sphere
$D_Lcylinder = filter_input(INPUT_POST, 'D_Lcylinder'); // Distance cylinder
$D_Laxis = filter_input(INPUT_POST, 'D_Laxis');      // Distance axis
// ... similar for right eye and near vision
```

---

### 4. **saveDailyEntry()** - Financial Journal Integration
**Location**: Line 820  
**Purpose**: Create comprehensive accounting entries for optical sales

**Function Signature**:
```php
function saveDailyEntry($insurance, $card, $cash, $waitvalue, $billId, $offline)
```

**Accounting Logic**:
1. **Credit Entries**: Sales revenue to appropriate accounts
2. **Debit Entries**: Cash, receivables, insurance claims
3. **Discount Handling**: Insurance and payment network fees
4. **Cost Center Integration**: Project-based accounting
5. **Multi-currency Support**: Different payment methods

**Account Structure**:
```php
// Main accounts used
$salesAccount = 16;        // Sales revenue
$cashAccount = $save->treeId;      // Cash register
$receivablesAccount = $client->treeId; // Customer receivables
$insuranceAccount = $insurance->treeId; // Insurance claims
```

---

### 5. **saveBillProducts()** - Product Processing & Inventory
**Location**: Line 1256  
**Purpose**: Process bill line items with inventory management

**Function Signature**:
```php
function saveBillProducts($billId, $offline, $affectNetworkNow = 0)
// Returns: Flag indicating inventory issues
```

**Process Flow**:
1. **Product Validation**: Check product IDs and quantities
2. **Inventory Updates**: Decrease stock quantities
3. **Cost Tracking**: Update last/mean buy prices
4. **Store Reports**: Log inventory movements
5. **Service Handling**: Skip inventory for service items

**Inventory Logic**:
```php
if ($product->isService != 1) {
    $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeId);
    $productbefore = $storeDetail->productquantity;
    $productafter = $productbefore - $productNum;
    $storeDetail->productquantity = $productafter;
    $storeDetailDAO->update($storeDetail);
    
    if ($storeDetail->productquantity < 0) {
        $flag = 1; // Negative inventory warning
    }
}
```

---

### 6. **updateClientDebt()** - Customer Account Management
**Location**: Line 104  
**Purpose**: Update customer debt balances with proper tracking

**Function Signature**:
```php
function updateClientDebt($clientid, $clientdebtAfter, $offline)
```

**Process Flow**:
1. Set appropriate user ID (online/offline)
2. Update client debt balance
3. Maintain audit trail

---

### 7. **insertClientdebtchangeupdate()** - Debt Change Tracking
**Location**: Line 125  
**Purpose**: Log all customer debt changes for audit and reporting

**Function Signature**:
```php
function insertClientdebtchangeupdate($clientid, $before, $amount, $type, 
    $processname, $modelid, $after, $tablename, $comment, $totalCost, $date, $offline)
```

**Tracking Fields**:
- **Before/After**: Debt balances
- **Amount/Type**: Change amount and direction (0=increase, 1=decrease)
- **Process**: Source operation description
- **Model ID**: Link to source document
- **Table Name**: Source controller/table

---

### 8. **getBillDetails()** - Bill Display Processing
**Location**: Line 1346  
**Purpose**: Load and format bill data for display/printing

**Function Signature**:
```php
function getBillDetails($billId)
```

**Data Assembly**:
1. **Bill Master**: Load main bill record
2. **Client Data**: Customer information
3. **Insurance Data**: Insurance company details if applicable
4. **Payment Networks**: Card payment details
5. **Medical Data**: Eye examination results
6. **Products**: Line items with categories
7. **Branch Info**: Store location details

---

## 🔄 Workflows

### Workflow 1: Complete Optical Sales Bill Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Optical Sales Bill               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Bill Initialization                                     │
│     - Parse POST parameters                                 │
│     - Validate client and date information                  │
│     - Generate bill number (offline) or validate (online)   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Medical Examination Processing                          │
│     IF kashf required:                                      │
│       │                                                     │
│       ├─→ External Kashf: Save location and date           │
│       │                                                     │
│       ├─→ Internal Kashf:                                  │
│       │   ├─ Create kashf master record                    │
│       │   ├─ Save eye examination details                  │
│       │   │  (sphere, cylinder, axis for both eyes)       │
│       │   ├─ Record ADD values and notes                   │
│       │   └─ Mark kashf as used                            │
│       │                                                     │
│       └─→ No Kashf: Skip medical processing                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Payment Method Processing                               │
│     FOR EACH selected payment method:                       │
│       │                                                     │
│       ├─→ Cash Payment:                                     │
│       │   └─ Record cash amount and register               │
│       │                                                     │
│       ├─→ Insurance Payment:                                │
│       │   ├─ Load insurance company details                │
│       │   ├─ Calculate customer/company portions           │
│       │   ├─ Apply insurance discount percentage           │
│       │   └─ Upload insurance documents                    │
│       │                                                     │
│       └─→ Card Payment:                                     │
│           ├─ Record payment network details                │
│           ├─ Calculate network fees/discounts              │
│           └─ Process card transaction data                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Product Processing                                      │
│     FOR EACH product on bill:                               │
│       │                                                     │
│       ├─→ Validate product and quantity                    │
│       │                                                     │
│       ├─→ Create billsproducts record                      │
│       │                                                     │
│       ├─→ Update inventory (if not service):               │
│       │   ├─ Get current stock quantity                    │
│       │   ├─ Decrease by sold quantity                     │
│       │   ├─ Check for negative inventory                  │
│       │   └─ Log inventory movement                        │
│       │                                                     │
│       └─→ Update product cost tracking                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Financial Processing                                    │
│     Customer Debt Management:                               │
│       ├─ Calculate debt change                             │
│       ├─ Update customer debt balance                      │
│       └─ Log debt change transaction                       │
│                                                             │
│     Accounting Entries:                                     │
│       ├─ Create daily entry header                         │
│       ├─ Credit sales account                              │
│       ├─ Debit payment accounts (cash/insurance/card)      │
│       ├─ Handle discounts and fees                         │
│       └─ Link entry to bill record                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Finalization                                            │
│     - Commit database transaction                           │
│     - Return bill ID and status                             │
│     - Handle any processing errors                          │
│     - Update bill with daily entry ID                       │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Medical Examination Integration
```
┌─────────────────────────────────────────────────────────────┐
│            START: Eye Examination Processing                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Examination Type Determination                          │
│     kashftype values:                                       │
│       │                                                     │
│       ├─→ -1: No examination required                      │
│       ├─→ 0: Internal examination                          │
│       └─→ 1: External examination                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Internal Examination Processing                         │
│     Create doctorkashf record:                              │
│       │                                                     │
│       ├─→ Left Eye Distance (D):                           │
│       │   ├─ Sphere, Cylinder, Axis                        │
│       │   └─ Prism, Visual Acuity                          │
│       │                                                     │
│       ├─→ Left Eye Near (N):                               │
│       │   ├─ Sphere, Cylinder, Axis                        │
│       │   └─ Prism, Visual Acuity                          │
│       │                                                     │
│       ├─→ Right Eye Distance (D):                          │
│       │   ├─ Sphere, Cylinder, Axis                        │
│       │   └─ Prism, Visual Acuity                          │
│       │                                                     │
│       ├─→ Right Eye Near (N):                              │
│       │   ├─ Sphere, Cylinder, Axis                        │
│       │   └─ Prism, Visual Acuity                          │
│       │                                                     │
│       └─→ Additional Data:                                  │
│           ├─ ADD values (right/left)                       │
│           ├─ Bifocal measurements                          │
│           ├─ PD (Pupillary Distance)                       │
│           ├─ BVD (Back Vertex Distance)                    │
│           └─ Clinical notes                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. External Examination Handling                           │
│     - Record examination location                           │
│     - Store examination date                                │
│     - Link to existing examination records                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Examination Integration                                 │
│     - Link examination to bill record                       │
│     - Update examination payment status                     │
│     - Apply any examination-based discounts                 │
└─────────────────────────────────────────────────────────────┘
```

---

## 🧮 Complex Calculation Methods

### Insurance Payment Calculation
```php
function saveInsurancePayment($bills, $offline) {
    $bills->customerpercent = $_POST['clientPercent'];
    $bills->customermax = $_POST['clientMax'];
    $bills->customercarry = $_POST['clientCarry'];
    $bills->companyaccept = $_POST['insAccept'];
    $bills->companycarry = $_POST['insuranceValue'];
    
    // Apply insurance company discount
    $bills->insdiscountpercent = $insuranceCompanies->discountpercent;
    
    return $bills;
}
```

### Payment Network Fee Calculation
```php
function saveCardPayment($bills, $offline) {
    $bills->paymentnetworkid = $_POST['paymentNetworks'];
    $bills->cardvalue = $_POST['cardValue'];
    $bills->netdiscountpercent = $paymentNetworks->discountpercent;
    
    // Calculate network fee
    $cardValue = $_POST['cardValue'];
    $cardDiscount = $cardValue * ($bills->netdiscountpercent) / 100;
    $netAmount = $cardValue - $cardDiscount;
    
    return $bills;
}
```

### Product Cost Tracking
```php
function lastAndMeanBuyPrice_SellOptic($detailId, $productId) {
    $buyProduct = $productDAO->load($productId);
    
    // Use existing costs or default to buy price
    if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
        $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
    }
    if ($buyProduct->lastbuyprice == NULL || $buyProduct->lastbuyprice == 0) {
        $buyProduct->lastbuyprice = $buyProduct->productBuyPrice;
    }
    
    // Update sell record with cost information
    $billsProductsEX->updatePrices_f_optic($buyProduct->lastbuyprice, 
                                          $buyProduct->meanbuyprice, 
                                          $detailId);
}
```

---

## 🔒 Security & Permissions

### Transaction Management
```php
$mytransactions = new Transaction();
try {
    // All database operations
    $mytransactions->commit();
} catch (Exception $ex) {
    $mytransactions->rollback();
}
```

### Input Sanitization
```php
$clientId = filter_input(INPUT_POST, "client");
$billDate = filter_input(INPUT_POST, "billdate");
$productstotalprice = filter_input(INPUT_POST, "totalBillPrice");
```

### Session Management
- User ID validation from `$_SESSION['userid']`
- Branch ID from `$_SESSION['branchId']`
- Save ID from `$_SESSION['saveid']`

---

## 📊 Performance Considerations

### Database Optimization
1. **Critical Indexes**:
   - `bills(clientid, billdate, deleted)`
   - `billsproducts(billid, productid)`
   - `storedetail(productid, storeid)`
   - `clientdebtchange(clientid, clientdebtchangedate)`

2. **Transaction Efficiency**:
   - Batch product processing
   - Minimize database calls in loops
   - Use prepared statements via DAO layer

3. **Inventory Management**:
   - Real-time stock updates
   - Negative inventory warnings
   - Store movement logging

---

## 🚀 Future Enhancement Opportunities

### 1. **Advanced Medical Integration**
- Digital prescription import
- OCT scan integration
- Automated lens recommendations
- Prescription history tracking

### 2. **Enhanced Payment Processing**
- Real-time card authorization
- Digital wallet integration
- Installment payment plans
- Loyalty program integration

### 3. **Inventory Optimization**
- Automatic reorder points
- Supplier integration
- Barcode scanning
- Serial number tracking

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [sellbillController.md](sellbillController.md) - Sales operations
- [buyBillController.md](buyBillController.md) - Purchase operations

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When billing system enhancements are implemented