# Offer Order Controller Documentation

**File**: `/controllers/offerorder.php`  
**Purpose**: Manages product offer orders with client data integration and product tracking  
**Last Updated**: December 20, 2024  
**Total Functions**: 1  
**Lines of Code**: ~285

---

## 📋 Overview

The Offer Order Controller is a specialized module that handles order management from existing client offers. It processes order creation based on previous offer data and manages the relationship between offers, orders, and products.

### Primary Functions
- [x] Display offer-to-order conversion form
- [x] Process order creation from existing offers
- [x] View all orders with client information
- [x] Display detailed order information
- [x] Edit existing orders
- [x] Handle order status changes
- [x] Product quantity tracking with store/available/minus states

### Related Controllers
- [offerclient.php](offerclient.md) - Client offer management
- [sellbillController.php](sellbillController.md) - Sales operations
- [productController.php](productController.md) - Product management
- [clientController.php](clientController.md) - Customer management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **offerorder** | Order master data from offers | id, datenow, userid, del, client, mydate, alltotal, allquantity, allquantstore, pricestore, allquantavailable, priceavailable, allquantmiun, pricemiun, oldoffer, oldorder |
| **offerproorder** | Order product details | clientid, productid, quantity, storequant, availablequant, miunquant, price, total |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **offerclient** | Source offer client data | id, client, datenow, userid, del, mydate, alltotal, allquantity, oldoffer |
| **offerproduct** | Source offer product data | clientid, productid, quantity, price, total, storequant, availablequant, miunquant |
| **client** | Customer master data | clientid, clientname |
| **product** | Product master data | productId, productName, logo |

---

## 🔑 Key Functions

### 1. **Default Action (empty $do)** - Display Order Form
**Location**: Line 95  
**Purpose**: Load offer data and display order creation form

**Process Flow**:
1. Load offer client data by ID
2. Retrieve client name from client table
3. Load all offer products for the client
4. Enhance product data with names and logos
5. Display via `offerorder/add.html` template

**Function Signature**:
```php
// Triggered when: No action specified
$id = filter_input(INPUT_GET, 'id');
$offerClient = $offerClientDAO->load($id);
$client = $clientDAO->load($offerClient->client);
$offerProduct = $offerProductDAO->queryByClientid($offerClientid);
```

---

### 2. **add()** - Create Order from Offer
**Location**: Line 209  
**Purpose**: Convert existing offer data into a new order

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

**Process Flow**:
1. Extract form data for order header
2. Create new order record with all quantities and prices
3. Process all product line items
4. Insert order details for each product
5. Track store quantities, available quantities, and minus quantities

**Key Variables**:
- `$alltotal` - Total order value
- `$allquantity` - Total quantity ordered
- `$allquantstore` - Total store quantity
- `$allquantavailable` - Total available quantity
- `$allquantminus` - Total minus quantity
- `$oldoffer` - Reference to original offer
- `$oldorder` - Reference to any existing order

**Product Processing Logic**:
```php
for ($i = 1; $i <= $itr; $i++) {
    if (isset($_POST['product' . $i]) && !empty($_POST['product' . $i])) {
        $product = filter_input(INPUT_POST, 'product' . $i);
        $quantproduct = filter_input(INPUT_POST, 'quantity' . $i);
        $quantstore = filter_input(INPUT_POST, 'prostore' . $i);
        $quantavailable = filter_input(INPUT_POST, 'proavailable' . $i);
        $quantminus = filter_input(INPUT_POST, 'prominus' . $i);
        $price = filter_input(INPUT_POST, 'price' . $i);
        $total = filter_input(INPUT_POST, 'total' . $i);
        
        $offerProorder->clientid = $id;
        $offerProorder->productid = $product;
        $offerProorder->quantity = $quantproduct;
        // ... other assignments
        $offerProorderDAO->insert($offerProorder);
    }
}
```

---

### 3. **show** - List All Orders
**Location**: Line 127  
**Purpose**: Display all orders with client information

**Process Flow**:
1. Query all order records
2. Load client names for each order
3. Display via `offerorder/show.html` template

---

### 4. **detail** - Show Order Details
**Location**: Line 136  
**Purpose**: Display complete order information with products

**Process Flow**:
1. Load order by ID
2. Retrieve client information
3. Load all order product details
4. Enhance with product names and logos
5. Display via `offerorder/detail.html` template

---

### 5. **edit** - Edit Order Form
**Location**: Line 174  
**Purpose**: Display order editing interface

**Process Flow**:
1. Load existing order data
2. Load client and product information
3. Prepare data for editing
4. Display via `offerorder/edit.html` template

---

### 6. **change** - Update Order Status
**Location**: Line 153  
**Purpose**: Handle order status changes (cancel/approve/pending)

**Process Flow**:
1. Receive order ID and new status
2. Load offer client record
3. Update del field based on status:
   - `0` = active/pending
   - `1` = approved
   - `3` = cancelled/deleted

**Status Logic**:
```php
if ($name == 3) {
    $offerClient->del = 3; // Cancelled
} elseif($name == 1) {
    $offerClient->del = 1; // Approved
} else {
    $offerClient->del = 0; // Active
}
```

---

## 🔄 Workflows

### Workflow 1: Order Creation from Offer
```
┌─────────────────────────────────────────────────────────────┐
│              START: Select Existing Offer                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Offer Data                                         │
│     - Get offer client information                          │
│     - Load associated client details                        │
│     - Retrieve all offer products                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Display Order Form                                      │
│     - Show client information                               │
│     - Display product list with quantities                  │
│     - Show store/available/minus quantities                 │
│     - Allow quantity adjustments                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Order Creation                                  │
│     - Validate form data                                    │
│     - Create order header record                            │
│     - Process each product line item                        │
│     - Calculate totals and quantities                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Order Data                                         │
│     - Insert offerorder record                              │
│     - Insert offerproorder records for each product         │
│     - Link to original offer (oldoffer field)              │
│     - Set initial status                                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display order creation form from offer |
| `do=add` | `add()` | Process new order creation |
| `do=show` | Show action | List all orders with client information |
| `do=detail` | Detail action | Show complete order details |
| `do=edit` | Edit action | Display order editing interface |
| `do=change` | Change action | Update order status via AJAX |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Required Parameters by Action

**Order Creation Form** (`do=` empty):
- `id` - Offer client ID to base order on

**Order Processing** (`do=add`):
- `client` - Client ID
- `mydate` - Order date
- `alltotal` - Total order value
- `allquantity` - Total quantity
- `itr` - Number of product iterations
- `product{N}` - Product ID for line N
- `quantity{N}` - Quantity for product N
- `price{N}` - Price for product N

**Order Details** (`do=detail`):
- `id` - Order ID

**Status Change** (`do=change`):
- `id` - Order ID
- `date` - New status value

---

## 🧮 Calculation Methods

### Quantity Tracking
```php
// Store quantity tracking
$offerProorder->storequant = $quantstore;      // Available in store
$offerProorder->availablequant = $quantavailable; // Available for order
$offerProorder->miunquant = $quantminus;       // Minus/shortage quantity

// Total calculations
$allquantity += $quantproduct;                 // Sum all ordered quantities
$allquantstore += $quantstore;                 // Sum all store quantities
$allquantavailable += $quantavailable;         // Sum all available
$allquantminus += $quantminus;                 // Sum all shortages
```

### Price Calculations
```php
// Line total calculation
$total = $quantity * $price;

// Order total calculation
$alltotal = array_sum($all_line_totals);

// Price storage with different quantity types
$pricestore = $price_for_store_quantity;
$priceavailable = $price_for_available_quantity;
$pricestminus = $price_for_minus_quantity;
```

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
// All actions require authentication
include_once("../public/authentication.php");
```

### Input Validation
- All inputs use `filter_input()` for sanitization
- Numeric values properly cast to integers
- Required fields validated before processing

### Session Management
- User ID tracked: `$_SESSION["userid"]`
- Order ownership validation through user sessions

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `offerorder(client, mydate)`
   - `offerproorder(clientid, productid)`
   - `offerclient(id)`
   - `offerproduct(clientid)`

2. **Query Optimization**:
   - Batch product loading by client ID
   - Single queries for client information
   - Efficient product name/logo loading

3. **Memory Management**:
   - Limit product iterations in forms
   - Clean up large product arrays after processing

---

## 🐛 Common Issues & Troubleshooting

### 1. **Missing Product Information**
**Issue**: Products show without names or logos  
**Cause**: Product loading issue in offer display

**Debug**:
```sql
SELECT * FROM offerproduct op 
LEFT JOIN product p ON p.productId = op.productid 
WHERE op.clientid = [ID];
```

### 2. **Quantity Calculation Errors**
**Issue**: Total quantities don't match line items  
**Cause**: Missing or invalid quantity inputs

**Fix**: Validate all quantity fields:
```php
// Ensure numeric values
$quantity = (int) filter_input(INPUT_POST, 'quantity' . $i);
if ($quantity <= 0) continue; // Skip invalid quantities
```

### 3. **Order Status Issues**
**Issue**: Status changes not reflected  
**Cause**: AJAX request failures or database update problems

**Debug**:
```sql
SELECT * FROM offerclient WHERE id = [ID];
-- Check del field: 0=active, 1=approved, 3=cancelled
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Order Creation
```
1. Create an offer with multiple products
2. Navigate to order creation (/?id=[OFFER_ID])
3. Verify all offer products load correctly
4. Submit order with modified quantities
5. Check offerorder and offerproorder tables
6. Verify totals calculated correctly
```

### Test Case 2: Order Status Management
```
1. Create test order from offer
2. Use AJAX change action with different statuses
3. Verify del field updates correctly
4. Test status transitions: 0→1→3→0
5. Check status persistence after refresh
```

### Test Case 3: Data Integrity
```
1. Create order with edge case quantities (0, negative)
2. Test with non-existent product IDs
3. Verify error handling for invalid client IDs
4. Test concurrent order creation
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [offerclient.md](offerclient.md) - Client offer management
- [sellbillController.md](sellbillController.md) - Sales operations
- [Database Schema Documentation](#) - Table relationships

---

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