# Rent Products Controller Documentation

**File**: `/controllers/rentproducts.php`  
**Purpose**: Manages rental products inventory including purchase, rental pricing, and lifecycle management  
**Last Updated**: December 20, 2024  
**Total Functions**: 8  
**Lines of Code**: ~460

---

## 📋 Overview

The Rent Products Controller manages a specialized rental inventory system for products that are purchased and then rented out to customers. It handles the complete lifecycle from product acquisition to rental management, including financial transactions for both cash and credit purchases.

### Primary Functions
- [x] Add new rental products with purchase details
- [x] Manage rental pricing and availability
- [x] Track product quantities and rental status
- [x] Handle cash and supplier credit purchases
- [x] Update rental product information
- [x] Soft delete rental products
- [x] Integration with accounting system (daily entries)
- [x] Supplier debt management

### Related Controllers
- [supplierController.php](#) - Supplier management
- [saveController.php](#) - Cash management
- [dailyentry.php](#) - Accounting entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **rentproduct** | Rental products master | id, name, buyprice, rentprice, quantity, paytype, supplierid, totalprice, createdate, isdel, dailyentryid |
| **rentstore** | Rental inventory tracking | id, rentproductid, amount, rented |

### Financial Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers/safes | saveid, savename, savecurrentvalue, treeId |
| **savedaily** | Cash transaction log | savedailyid, saveid, savedailychangeamount, savedailychangetype, processname, savedailymodelid |
| **supplier** | Suppliers master data | supplierid, suppliername, suppliercurrentDebt, treeId |
| **supplierdebtchange** | Supplier debt transactions | supplierdebtchangeid, supplierid, supplierdebtchangeamount, supplierdebtchangetype, tablename |

### Accounting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **dailyentry** | Journal entries | dailyentryid, entryComment, reverseofid |
| **dailyentrycreditor** | Credit entries | dailyentrycreditorid, dailyentryid, accountstreeid, value |
| **dailyentrydebtor** | Debit entries | dailyentrydebtorId, dailyentryid, accountstreeid, value |
| **accountstree** | Chart of accounts | accountstreeid, accountname |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Form Display
**Location**: Lines 113-121  
**Purpose**: Display form for adding new rental products

**Process Flow**:
1. Load all suppliers for dropdown
2. Display add form template
3. Include authentication check

**Template**: `rent/products/add.html`

---

### 2. **add()** - Add New Rental Product
**Location**: Lines 122-315  
**Purpose**: Create new rental product with financial transactions

**Function Signature**:
```php
// POST Parameters
$name = filter_input(INPUT_POST, 'name');
$info = filter_input(INPUT_POST, 'info');
$amount = filter_input(INPUT_POST, 'amount');
$buyprice = filter_input(INPUT_POST, 'buyprice');
$totalprice = filter_input(INPUT_POST, 'totalprice');
$rentprice = filter_input(INPUT_POST, 'rentprice');
$paytype = filter_input(INPUT_POST, 'paytype'); // 0=cash, 1=credit
$supplierid = filter_input(INPUT_POST, 'supplierid');
```

**Process Flow**:
1. **Duplicate Check**: Verify product name doesn't exist
2. **Product Creation**: Insert into `rentproduct` table
3. **Inventory Setup**: Create `rentstore` record with quantity
4. **Payment Processing**:
   - **Cash Payment (paytype=0)**:
     - Decrease save balance
     - Update save daily report
     - Create accounting entry (Debit: Purchases, Credit: Cash)
   - **Credit Payment (paytype=1)**:
     - Increase supplier debt
     - Log supplier debt change
     - Create accounting entry (Debit: Purchases, Credit: Supplier)
5. **Update Product**: Link daily entry ID to product

**Accounting Entries**:
```php
// Cash Purchase
Debit: Purchases (Account ID: 12) = $totalprice
Credit: Cash Save (Account: save->treeId) = $totalprice

// Credit Purchase  
Debit: Purchases (Account ID: 12) = $totalprice
Credit: Supplier (Account: supplier->treeId) = $totalprice
```

**Validation**:
- Duplicate name prevention
- Required field validation
- Numeric validation for prices and quantities

---

### 3. **show()** - Display Rental Products List
**Location**: Lines 316-326  
**Purpose**: Show all non-deleted rental products with management options

**Process Flow**:
1. Query all active rental products (`isdel = 0`)
2. Load YouTube tutorial links
3. Display with delete/edit controls

**Template**: `rent/products/show.html`

---

### 4. **edit()** - Edit Form Display
**Location**: Lines 327-337  
**Purpose**: Display edit form for existing rental product

**Process Flow**:
1. Load product data by ID
2. Load suppliers for dropdown
3. Display edit form

**Template**: `rent/products/edit.html`

---

### 5. **update()** - Update Rental Product
**Location**: Lines 349-423  
**Purpose**: Update rental product information with accounting adjustments

**Function Signature**:
```php
$name = filter_input(INPUT_POST, 'name');
$info = filter_input(INPUT_POST, 'info');
$buyprice = filter_input(INPUT_POST, 'buyprice');
$totalprice = filter_input(INPUT_POST, 'totalprice');
$rentprice = filter_input(INPUT_POST, 'rentprice');
$id = filter_input(INPUT_POST, 'id');
```

**Process Flow**:
1. **Load Original Product**: Get existing product data
2. **Reverse Original Entry**: Reverse existing daily entry
3. **Create New Entry**: Generate new accounting entry based on payment type
4. **Update Product**: Save new product information
5. **Transaction Management**: Commit or rollback on error

**Key Features**:
- Accounting entry reversal and recreation
- Price update capability
- Transaction safety with rollback

---

### 6. **tempdelete()** - Soft Delete Product
**Location**: Lines 424-445  
**Purpose**: Soft delete rental product and reverse accounting entries

**Process Flow**:
1. Mark product as deleted (`isdel = 1`)
2. Reverse associated daily entry
3. Transaction safety with commit/rollback

**Note**: This is a soft delete - product remains in database but marked as deleted

---

## 🔄 Workflows

### Workflow 1: Cash Purchase Rental Product
```
┌─────────────────────────────────────────────────────────────┐
│         START: Add New Rental Product (Cash)               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Validate Input & Check Duplicates                      │
│     - Check product name uniqueness                        │
│     - Validate required fields                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Create Product & Store Records                          │
│     - Insert into rentproduct table                        │
│     - Create rentstore inventory record                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Cash Payment                                    │
│     - Get current save balance                              │
│     - Decrease save balance by total price                  │
│     - Update save table                                     │
│     - Insert savedaily transaction                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Create Accounting Entry                                 │
│     - Debit: Purchases Account (ID: 12)                    │
│     - Credit: Cash Save Account (treeId)                   │
│     - Link daily entry to product record                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Update Product with Daily Entry ID                     │
│     - Link accounting entry to product                     │
│     - Complete transaction                                  │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Supplier Credit Purchase
```
┌─────────────────────────────────────────────────────────────┐
│       START: Add New Rental Product (Credit)               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Validate Input & Create Product                         │
│     - Same as cash purchase workflow                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Supplier Credit                                 │
│     - Get current supplier debt                             │
│     - Increase supplier debt by total price                 │
│     - Update supplier table                                 │
│     - Insert supplierdebtchange record                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Accounting Entry                                 │
│     - Debit: Purchases Account (ID: 12)                    │
│     - Credit: Supplier Account (supplier->treeId)          │
│     - Link daily entry to product record                   │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| (empty) | Default action | Display add form |
| `do=add` | `add()` | Process new product creation |
| `do=show` | `show()` | Display products list |
| `do=edit` | `edit()` | Display edit form |
| `do=editprint` | Print edit | Display print-friendly edit |
| `do=update` | `update()` | Process product updates |
| `do=tempdelete` | `tempdelete()` | Soft delete product |
| `do=sucess` | Success | Show success page |
| `do=error` | Error | Show error page |

### Required Parameters by Action

**Add Product** (`do=add`):
- `name` - Product name (required, unique)
- `info` - Product description
- `amount` - Initial quantity
- `buyprice` - Purchase price per unit
- `totalprice` - Total purchase cost
- `rentprice` - Rental price per period
- `paytype` - Payment type (0=cash, 1=credit)
- `supplierid` - Supplier ID

**Edit Product** (`do=edit`):
- `id` - Product ID

**Update Product** (`do=update`):
- `id` - Product ID
- `name` - Updated product name
- `buyprice` - Updated purchase price
- `rentprice` - Updated rental price
- `totalprice` - Updated total price

**Delete Product** (`do=tempdelete`):
- `id` - Product ID
- `dailyentryid` - Daily entry ID to reverse

---

## 🧮 Calculation Methods

### Purchase Cost Calculation
```php
// Total cost validation
$totalprice = $buyprice * $amount; // Should match user input
```

### Cash Flow Management
```php
// Cash purchase impact
$balanceBefore = $saveinfo->savecurrentvalue;
$balanceAfter = $balanceBefore - $totalprice;

// Validation check
if ($balanceAfter < 0) {
    // Insufficient funds error
}
```

### Supplier Debt Calculation
```php
// Credit purchase impact
$debtBefore = $supplierinfo->suppliercurrentDebt;
$debtAfter = $debtBefore + $totalprice;
```

### Rental Profitability
```php
// Break-even calculation (implied)
$breakEvenRentals = $buyprice / $rentprice;
```

---

## 🔒 Security & Permissions

### Authentication
```php
include_once("../public/authentication.php");
```
- All actions require valid user session
- Session-based user ID tracking

### Input Validation
```php
$name = filter_input(INPUT_POST, 'name');
$amount = filter_input(INPUT_POST, 'amount');
$buyprice = filter_input(INPUT_POST, 'buyprice');
```
- PHP filter_input() for basic sanitization
- Duplicate name prevention
- Numeric validation for prices

### Data Integrity
- Transaction management with commit/rollback
- Accounting entry reversal on updates/deletes
- Soft delete preservation of historical data

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Recommended**:
   - `rentproduct(name)` for duplicate checking
   - `rentproduct(isdel)` for active product queries
   - `rentstore(rentproductid)` for inventory lookups
   - `supplierdebtchange(supplierid, tablename)` for debt tracking

2. **Query Efficiency**:
   - Single product insert per transaction
   - Batch operations for related tables
   - Proper use of transactions

### Memory Management
- Minimal data loading in forms
- Efficient supplier dropdown loading
- Clean object instantiation

### Known Performance Issues
```php
// Potential issue: Loading all suppliers for dropdown
$suppliers = $mysupplier->queryAll();
// Consider pagination for large supplier lists
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Duplicate Product Names**
**Issue**: Error when adding products with existing names  
**Cause**: Duplicate check in add() function

**Solution**:
```php
$checkduplicate = $myrentProducts->queryByName($name);
if (count($checkduplicate) > 0) {
    // Handle duplicate error
}
```

### 2. **Insufficient Cash Balance**
**Issue**: Cash purchases failing with negative balance  
**Cause**: No balance validation before save update

**Debug**:
```sql
SELECT savecurrentvalue FROM save WHERE saveid = [SESSION_SAVE_ID];
```

### 3. **Accounting Entry Imbalance**
**Issue**: Debit/Credit entries don't balance  
**Cause**: Incorrect account tree ID assignment

**Fix**:
```php
// Verify account tree IDs exist
$saveTreeId = $dataSave->treeId;  // Cash account
$supplierTreeId = $oldSupplier->treeId;  // Supplier account
```

### 4. **Transaction Rollback Issues**
**Issue**: Partial data saved when errors occur  
**Cause**: Missing transaction management

**Fix**:
```php
$mytransactions = new Transaction();
try {
    // Operations here
    $mytransactions->commit();
} catch (Exception $exc) {
    $mytransactions->rollback();
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Cash Purchase
```
1. Select supplier and enter product details
2. Choose cash payment (paytype=0)
3. Verify sufficient save balance
4. Submit form
5. Check: Product created, inventory updated, cash decreased, accounting entry created
```

### Test Case 2: Credit Purchase
```
1. Enter product details
2. Choose credit payment (paytype=1)
3. Submit form
4. Check: Product created, supplier debt increased, accounting entry created
```

### Test Case 3: Product Update
```
1. Edit existing product
2. Change prices
3. Verify old accounting entry reversed
4. Check new accounting entry created
```

### Test Case 4: Product Deletion
```
1. Delete active product
2. Verify product marked isdel=1
3. Check accounting entry reversed
4. Verify product no longer appears in lists
```

### Debug Mode Enable
```php
// Add at top of file for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Debug accounting entries
echo "Daily Entry ID: " . $dailyId . "<br>";
echo "Total Price: " . $totalprice . "<br>";
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [supplierController.php](#) - Supplier management
- [saveController.php](#) - Cash management  
- [dailyentry.php](#) - Accounting system
- [Database Schema Documentation](#) - Table relationships

---

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