# Restaurant (Bills) Controller Documentation

**File**: `/controllers/resturant.php`  
**Purpose**: Comprehensive restaurant/retail billing system with POS functionality, workshop orders, and advanced payment processing  
**Last Updated**: December 21, 2024  
**Total Functions**: 13  
**Lines of Code**: ~1988

---

## 📋 Overview

The Restaurant Controller (also known as Bills Controller) is a sophisticated point-of-sale and billing management system designed for restaurants, retail stores, or service businesses. It provides comprehensive billing functionality with advanced features including insurance billing, workshop order management, multi-payment methods, and integrated accounting. The controller handles:

- Complete POS billing system with product selection and pricing
- Insurance company integration for medical/service billing
- Workshop order management and tracking
- Multi-payment method support (cash, credit, insurance)
- Product request fulfillment and management
- Advanced bill printing with multiple templates
- Client and customer management integration
- Inventory integration with automatic stock updates
- Daily entry (accounting) integration for financial tracking
- Branch-based operations and user permissions
- Excel export functionality for reporting
- Category-based product filtering and selection

### Primary Functions
- [x] Complete POS billing system
- [x] Insurance billing and claim processing
- [x] Workshop order creation and management
- [x] Multi-payment method processing
- [x] Product request fulfillment
- [x] Advanced bill printing (normal/insurance)
- [x] Client management integration
- [x] Inventory stock management
- [x] Accounting entry automation
- [x] Excel export and reporting
- [x] Category-based product organization
- [x] User permission and access control

### Related Controllers
- [billsController.php](#) - Alternative billing interface
- [clientController.php](#) - Customer management
- [productController.php](#) - Product management
- [workshopController.php](#) - Workshop operations
- [storedetailController.php](#) - Inventory management
- [dailyentryController.php](#) - Accounting integration

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **bills** | Main bill records | billid, billno, clientid, userid, billdate, totalamount, insurancecompanyid |
| **billsproducts** | Bill line items | billsproductid, billid, productid, quantity, productprice, totalproductprice |
| **billsbuy** | Purchase bills | billsbuyid, billno, supplierid, userid, billdate, totalamount |
| **billsproductsbuy** | Purchase line items | billsproductsbuyid, billsbuyid, productid, quantity, productprice |

### Workshop Management
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **toworkshoporder** | Workshop orders | toworkshoporderid, clientid, workshopid, orderdate, orderstatus |
| **toworkshoporderbill** | Workshop billing | toworkshoporderbillid, toworkshoporderid, billid |
| **workshop** | Workshop details | workshopid, workshopname, workshoptype |

### Product Management
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **product** | Product master | productId, productName, productCatId, productSellPrice |
| **productcat** | Product categories | productCatId, productCatName, productCatParent |
| **productrequest** | Product requests | productrequestid, productid, quantity, status, requestdate |
| **storedetail** | Inventory levels | storedetailid, productid, storeid, productquantity |

### Client and Payment
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer records | clientid, clientname, clientphone, clientaddress |
| **insurancecompanie** | Insurance providers | insurancecompanyid, companyname, companytype |
| **paymentnetwork** | Payment methods | paymentnetworkid, networkname, networktype |

### Configuration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **branch** | Organization branches | branchId, branchName |
| **store** | Store locations | storeId, storeName |
| **user** | System users | userid, employeename, usergroupid |
| **usergroup** | User permissions | usergroupid, groupname, permissions |

---

## 🔑 Key Functions

### 1. **Default Action** - Bill Creation Interface
**Location**: Line 267  
**Purpose**: Display the main billing interface with product selection and payment options

**Process Flow**:
1. Generate unique bill number based on branch and year
2. Load client data for customer selection
3. Load insurance companies for insurance billing
4. Load payment networks for payment processing
5. Handle product requests if specified
6. Check user permissions for direct save functionality
7. Display appropriate billing template (normal or category-based)

**Bill Number Generation**:
```php
$branchId = $_SESSION['branchId'];
$today = date('y');
$billNo = $branchId . $today;

$bills = $billsEX->searchInBillNo($billNo);
if (count($bills) > 0) {
    $billNo = $bills->billno + 1;
    if ($branchId == 0) {
        $billNo = '0' . $billNo;
    }
} else {
    $billNo .= '00001';
}
```

**Product Request Handling**:
```php
if ($isProductRequest == 1) {
    $choosedItemArr = $_POST['choosedItem'];
    foreach ($choosedItemArr as $productRequestId) {
        $productRequest = $productRequestDAO->load($productRequestId);
        array_push($productRequestArray, $productRequest);
        
        $product = $productDAO->load($productRequest->productid);
        $productRequest->productName = $product->productName;
        
        $parentId = $product->productCatId;
        $pathArr = getProductPath_recursive($parentId, $categories, 0);
        $productRequest->productName = $product->productName . '/' . $pathArr;
    }
}
```

---

### 2. **add()** - Bill Processing and Creation
**Location**: Line 441  
**Purpose**: Process new bill creation with inventory updates and accounting integration

**Process Flow**:
1. Process bill data from form submission
2. Validate product availability and pricing
3. Create bill record in database
4. Create bill product line items
5. Update inventory quantities
6. Create accounting entries
7. Handle different bill types (normal, insurance, category-based)
8. Return success/failure status with bill ID

**Error Handling**:
```php
if ($detailResult['flag'] == 99) {
    $note = "رقم الفاتورة موجود من قبل";
    $smarty->assign('errorNote', $note);
    $smarty->display("error.html");
} else {
    finishProductRequests();
    if ($flag == 1) {
        // Insufficient inventory
        $note = "لا يوجد كمية بالمخزن كافية للفاتورة";
        $smarty->assign('msgnote', $note);
        $smarty->display("notes2.html");
    } else {
        // Success - redirect based on bill type
        switch ($payType) {
            case "normal_bill":
                header("location:?do=empty");
                break;
            case "cate_bill":
                header("location:?do=addview2");
                break;
            // Additional cases...
        }
    }
}
```

---

### 3. **print / printbuy** - Bill Printing
**Location**: Lines 376, 408  
**Purpose**: Generate printable bill formats for different scenarios

**Print Types Supported**:
- **Normal Print** (type = 0): Standard bill format
- **Insurance Print** (type = 1): Insurance company format
- **Both Print** (type = 2): Both normal and insurance formats

**Process Flow**:
1. Get bill ID and print type from request
2. Load bill details via `getBillDetails()` or `getBillDetailsBuy()`
3. Determine lens display option
4. Display appropriate template(s) based on print type

**Template Selection**:
```php
if ($type == 2) {           // Both formats
    $smarty->display("billsview/print.html");
    $smarty->display("billsview/printins.html");
} elseif ($type == 1) {     // Insurance only
    $smarty->display("billsview/printins.html");
} else {                    // Normal only
    $smarty->display("billsview/print.html");
}
```

---

### 4. **saveDailyEntryDelete()** - Accounting Entry Deletion
**Location**: Line 1337  
**Purpose**: Remove daily accounting entries when bills are deleted

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

**Process Flow**:
1. Load bill details for accounting reversal
2. Create reversal entries for:
   - Client accounts (credit reversal)
   - Cash/payment accounts (debit reversal)
   - Sales revenue accounts (debit reversal)
3. Handle insurance billing reversals if applicable
4. Update account balances

---

### 5. **saveDailyEntryDeleteBuy()** - Purchase Entry Deletion
**Location**: Line 1458  
**Purpose**: Remove accounting entries for deleted purchase bills

**Similar to `saveDailyEntryDelete()` but handles purchase-side accounting**

---

### 6. **toworkshop()** - Workshop Order Creation
**Location**: Line 1581  
**Purpose**: Create workshop orders from bills for service processing

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

**Process Flow**:
1. Get bill and workshop details from request
2. Validate workshop availability and capacity
3. Create workshop order record
4. Link bill to workshop order
5. Update workshop status and scheduling
6. Generate workshop tracking number

---

### 7. **isUnique()** - Uniqueness Validation
**Location**: Line 1651  
**Purpose**: Validate bill number uniqueness

**Function Signature**:
```php
function isUnique($unique)
```

**Returns**: Boolean indicating if bill number is available

---

### 8. **tobranch()** - Branch Transfer
**Location**: Line 1661  
**Purpose**: Transfer bills or orders between branches

**Process Flow**:
1. Validate source and target branches
2. Update bill branch assignments
3. Handle inventory transfers if needed
4. Update user permissions and access
5. Create audit trail for transfer

---

### 9. **encrypt_url() / decrypt_url()** - URL Security
**Location**: Lines 1702, 1718  
**Purpose**: Encrypt/decrypt sensitive data in URLs

**Function Signatures**:
```php
function encrypt_url($string)
function decrypt_url($string)
```

**Usage**: Secure transmission of bill IDs and sensitive parameters in URLs

---

### 10. **dateTimeDiff()** - Date Calculation
**Location**: Line 1731  
**Purpose**: Calculate time differences for bill processing

**Function Signature**:
```php
function dateTimeDiff($dateTime1, $dateTime2)
```

**Returns**: Time difference for billing calculations and reporting

---

### 11. **finishProductRequests()** - Request Completion
**Location**: Line 1743  
**Purpose**: Mark product requests as fulfilled after bill creation

**Process Flow**:
1. Get product request IDs from bill session
2. Update request status to completed
3. Link requests to created bill
4. Update inventory allocation
5. Notify requesting users/departments

---

### 12. **getCategoryChilds()** - Category Hierarchy
**Location**: Line 1758  
**Purpose**: Build product category tree for filtering

**Function Signature**:
```php
function getCategoryChilds($parentid = 0)
```

**Process Flow**:
1. Start with root categories (parentid = 0)
2. Recursively load child categories
3. Build hierarchical structure for display
4. Return formatted category tree

---

### 13. **style() / styleBy()** - Reporting Functions
**Location**: Lines 1772, 1869  
**Purpose**: Generate various bill reports and statistics

**Process Flow**:
1. Parse date ranges and filters
2. Query bill data with aggregations
3. Calculate totals and statistics
4. Format data for display
5. Support multiple report formats (HTML, Excel)

---

## 🔄 Workflows

### Workflow 1: Bill Creation Process
```
┌─────────────────────────────────────────────────────────────┐
│                START: New Bill Creation                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initialize Bill Interface                               │
│     - Generate unique bill number                          │
│     - Load client data and payment options                 │
│     - Load insurance companies if applicable               │
│     - Check user permissions for direct save               │
│     - Handle any pending product requests                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Product Selection and Pricing                           │
│     - User selects products from catalog                   │
│     - System validates inventory availability              │
│     - Calculate pricing with discounts                     │
│     - Apply insurance rates if applicable                  │
│     - Handle category-based selection if enabled           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Bill Processing (add() function)                        │
│     - Validate bill number uniqueness                      │
│     - Check inventory sufficiency                          │
│     - Create main bill record                              │
│     - Create bill product line items                       │
│     - Update inventory quantities                          │
│     - Calculate totals and taxes                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Payment and Accounting Processing                       │
│     - Process payment method selection                     │
│     - Create daily accounting entries:                     │
│       ├─ Debit: Client account                            │
│       ├─ Credit: Sales revenue                            │
│       ├─ Credit: Inventory accounts                       │
│       └─ Handle insurance billing if applicable           │
│     - Update client balances                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Completion and Options                                  │
│     - Mark any fulfilled product requests                  │
│     - Generate bill for printing                           │
│     - Redirect based on user choice:                       │
│       ├─ Create new bill                                   │
│       ├─ Return to bill list                               │
│       └─ Print current bill                                │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Workshop Order Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Workshop Order Request                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Bill for Workshop Processing                     │
│     - Choose existing bill for workshop order             │
│     - Select target workshop for service                   │
│     - Specify order requirements and timeline              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Workshop Validation (toworkshop() function)            │
│     - Validate workshop availability                       │
│     - Check workshop capacity and scheduling              │
│     - Verify bill products are workshop-compatible         │
│     - Generate unique workshop order number               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Workshop Order                                   │
│     - Insert toworkshoporder record                       │
│     - Link bill to workshop via toworkshoporderbill       │
│     - Set initial order status and dates                   │
│     - Update workshop scheduling system                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Workshop Order Tracking                                │
│     - Workshop order ready for processing                  │
│     - Updates tracked through workshop management          │
│     - Bill remains linked for billing reconciliation      │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display main billing interface |
| `do=empty` | Default action | Alternative billing interface |
| `do=addview2` | Category billing | Category-based billing interface |
| `do=add` | `add()` | Process new bill creation |
| `do=print` | Print interface | Display bill for printing |
| `do=printbuy` | Print interface | Display purchase bill for printing |
| `do=toworkshop` | `toworkshop()` | Create workshop order |
| `do=tobranch` | `tobranch()` | Transfer to branch |
| `do=style` | `style()` | Generate reports |
| `do=styleby` | `styleBy()` | Generate filtered reports |

### Required Parameters by Action

**Bill Creation** (`do=add`):
- Bill details and product selections via comprehensive POST data
- Client information and payment methods
- Insurance details if applicable

**Bill Printing** (`do=print`, `do=printbuy`):
- `id` - Bill ID to print (via GET)
- `type` - Print type (0=normal, 1=insurance, 2=both, via GET)
- `go` - Return URL after printing (via GET)
- `lens` - Lens display option (via GET)

**Workshop Order** (`do=toworkshop`):
- Bill ID and workshop selection
- Order requirements and scheduling
- Workshop-specific parameters

**Reporting** (`do=style`, `do=styleby`):
- Date ranges and filter criteria
- Report type and format specifications
- User and branch filters

---

## 🧮 Calculation Methods

### Bill Totals and Pricing
```php
// Product line total
$lineTotal = $quantity * $unitPrice;

// Apply discount
if ($discountType == 'percentage') {
    $discountAmount = $lineTotal * ($discountPercent / 100);
} else {
    $discountAmount = $discountValue;
}
$lineTotal -= $discountAmount;

// Calculate tax
$taxAmount = $lineTotal * ($taxRate / 100);
$lineTotalWithTax = $lineTotal + $taxAmount;
```

### Insurance Billing Calculations
```php
// Insurance coverage calculation
$insuranceCoverage = $billTotal * ($coveragePercent / 100);
$clientPortion = $billTotal - $insuranceCoverage;
$insuranceClaimAmount = $insuranceCoverage;
```

### Inventory Updates
```php
// Decrease inventory for sales
$currentQuantity = $storeDetail->productquantity;
$newQuantity = $currentQuantity - $soldQuantity;
$storeDetail->productquantity = $newQuantity;
```

---

## 🔒 Security & Permissions

### Authentication
```php
include_once("../public/authentication.php");
```
- Required for all bill operations
- Session-based user validation

### User Permissions
- Branch-based access control
- Direct save permissions per user group
- Percentage discount limits per user group
- Store access restrictions

### Data Security
- URL encryption for sensitive parameters
- Bill number uniqueness validation
- Input sanitization via filter_input()
- Session-based security for user data

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Critical Indexes Required**:
   - `bills(billno, billdate, clientid)` - For bill queries
   - `billsproducts(billid, productid)` - For line item queries
   - `storedetail(productid, storeid)` - For inventory updates
   - `client(clientid)` - For customer lookups

2. **Query Optimization**:
   - Use transactions for bill creation
   - Batch inventory updates
   - Optimize category hierarchy queries

3. **Memory Management**:
   - Large product catalogs can impact performance
   - Consider pagination for product selection
   - Optimize image loading for product displays

---

## 🐛 Common Issues & Troubleshooting

### 1. **Bill Number Duplication**
**Issue**: Duplicate bill numbers generated  
**Cause**: Concurrency issues in number generation

**Solution**: Add database constraints and better locking

### 2. **Inventory Sync Issues**
**Issue**: Inventory quantities not updating correctly  
**Cause**: Transaction failures or rollback issues

**Debug**: Check transaction handling and error logging

### 3. **Insurance Billing Errors**
**Issue**: Insurance claims not processing  
**Cause**: Missing insurance company setup or configuration

**Solution**: Verify insurance company data and billing rules

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientController.php](#) - Customer management
- [productController.php](#) - Product management
- [workshopController.php](#) - Workshop operations
- [dailyentryController.php](#) - Accounting integration

---

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