# Show Controller Documentation

**File**: `/controllers/showController.php`  
**Purpose**: Displays product inventory reports with client-specific product availability and pricing information  
**Last Updated**: December 21, 2024  
**Total Functions**: 6  
**Lines of Code**: ~624

---

## 📋 Overview

The Show Controller manages comprehensive product display and reporting functionality for inventory management. It provides functionality for:
- Client-specific product availability reports
- Product quantity tracking (store, available, minus)
- Price management and calculations
- Historical data reporting
- Client-product relationship management
- Multi-level product categorization
- Inventory status tracking
- Product show data persistence

### Primary Functions
- [x] Generate client-product availability reports
- [x] Track product quantities across multiple states
- [x] Manage product pricing and totals
- [x] Handle client-specific product data
- [x] Process inventory calculations
- [x] Display formatted product reports
- [x] Manage product show configurations
- [x] Support bulk product operations

### Related Controllers
- [clientController.php](#) - Client management
- [productController.php](#) - Product management
- [storedetailController.php](#) - Inventory management
- [sellbillController.php](#) - Sales operations
- [buyBillController.php](#) - Purchase operations

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **proclientshow** | Client-product display records | id, client, mydate, alltotal, allquantity, allquantstore, pricestore, allquantavailable, priceavailable, allquantmiun, pricemiun, datenow, userid, del |
| **productshow** | Product detail records | id, clientid, productid, quantity, storequant, availablequant, miunquant, price, total |

### Referenced Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer information | clientid, clientname, clientaddress, clientphone |
| **product** | Product master data | productid, productname, productprice |
| **store** | Inventory stores | storeid, storename |
| **user** | System users | userid, username, employeename |

---

## 🔑 Key Functions

### 1. **Default Action** - Product Show Form
**Location**: Lines 87-95  
**Purpose**: Display the main product show creation interface

**Process Flow**:
1. Check user authentication
2. Display header template
3. Show product show creation form
4. Display footer template

---

### 2. **add()** - Product Show Creation
**Location**: Lines 187-248  
**Purpose**: Create comprehensive product show records with client and product details

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

**Process Flow**:
1. Extract client and summary data
2. Create main client show record
3. Process individual product iterations
4. Calculate totals and quantities
5. Store all related records
6. Return operation status

**Main Record Creation**:
```php
$proclientshow->datenow = $datenow;
$proclientshow->userid = $userid;
$proclientshow->del = $del;
$proclientshow->client = $client;
$proclientshow->mydate = $mydate;
$proclientshow->alltotal = $alltotal;
$proclientshow->allquantity = $allquantity;
$proclientshow->allquantstore = $allquantstore;
$proclientshow->pricestore = $pricestore;
$proclientshow->allquantavailable = $allquantavailable;
$proclientshow->priceavailable = $priceavailable;
$proclientshow->allquantmiun = $allquantminus;
$proclientshow->pricemiun = $pricestminus;
```

**Product Detail Processing**:
```php
$itr = filter_input(INPUT_POST, 'itr');
for ($i = 1; $i <= $itr; $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);
    
    $Productshow->clientid = $id;
    $Productshow->productid = $product;
    $Productshow->quantity = $quantproduct;
    $Productshow->storequant = $quantstore;
    $Productshow->availablequant = $quantavailable;
    $Productshow->miunquant = $quantminus;
    $Productshow->price = $price;
    $Productshow->total = $total;
    $ProductshowDAO->insert($Productshow);
}
```

---

### 3. **show** - Display Client Product Reports
**Location**: Lines 110-123  
**Purpose**: Display all client product show records with client name resolution

**Process Flow**:
1. Query all client show records
2. Resolve client names from client table
3. Assign data to template
4. Display formatted report

**Client Name Resolution**:
```php
$allclient = $proclientshowDAO->queryAll();
foreach ($allclient as $client) {
    $proclient = R::findOne('client', 'clientid = ' . $client->client);
    $client->proclient = $proclient->clientname;
}
```

---

### 4. **edit** - Load Show Data for Editing
**Location**: Lines 140-156  
**Purpose**: Load existing product show data for modification

**Process Flow**:
1. Load main client show record
2. Load associated product details
3. Assign data to template variables
4. Display edit form

**Data Loading**:
```php
$id = filter_input(INPUT_GET, 'id');
$allclient = $proclientshowDAO->load($id);
$clientid = $allclient->id;
$allpro = $ProductshowDAO->queryByClientid($clientid);
```

---

### 5. **update()** - Product Show Update
**Location**: Lines 285-350  
**Purpose**: Update existing product show records with new data

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

**Process Flow**:
1. Load existing main record
2. Update summary fields
3. Process product detail updates
4. Recalculate totals
5. Store updated records

**Update Logic**:
```php
$proclientshow = $proclientshowDAO->load($id);
$proclientshow->datenow = $datenow;
$proclientshow->userid = $userid;
$proclientshow->del = $del;
// ... update all fields

$id = $proclientshowDAO->update($proclientshow);

for ($i = 1; $i <= $itr; $i++) {
    $Productshow = $ProductshowDAO->load($id);
    // ... update product details
    $quantproduct += $quantproduct; // Quantity accumulation
    $ProductshowDAO->update($Productshow);
}
```

---

### 6. **change()** - Status Toggle
**Location**: Lines 250-273 and 124-139  
**Purpose**: Toggle deletion status of product show records

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

**Process Flow**:
1. Get record ID and status value
2. Load existing record
3. Toggle deletion status
4. Update record
5. Return success status

**Toggle Logic**:
```php
$id = filter_input(INPUT_POST, 'id');
$name = filter_input(INPUT_POST, 'date');
if ($name == 1) {
    $proclientshow = $proclientshowDAO->load($id);
    $proclientshow->del = 1; // Mark as deleted
    $proclientshowDAO->update($proclientshow);
} else {
    $proclientshow = $proclientshowDAO->load($id);
    $proclientshow->del = 0; // Restore
    $proclientshowDAO->update($proclientshow);
}
```

---

## 🔄 Workflows

### Workflow 1: Product Show Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Product Show Report             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Client and Date                                  │
│     - Choose client from dropdown                           │
│     - Set report date                                       │
│     - Initialize summary totals                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Add Product Details                                     │
│     FOR EACH product in report:                             │
│       │                                                     │
│       ├─→ Select product                                   │
│       │                                                     │
│       ├─→ Enter quantities:                                │
│       │   ├─ Total quantity                                │
│       │   ├─ Store quantity                                │
│       │   ├─ Available quantity                            │
│       │   └─ Minus quantity (shortfalls)                   │
│       │                                                     │
│       ├─→ Set price and calculate total                    │
│       │                                                     │
│       └─→ Add to product list                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Calculate Summary Totals                                │
│     - Sum all product quantities                            │
│     - Calculate total store quantities                      │
│     - Sum available quantities                              │
│     - Calculate minus quantities                            │
│     - Compute price totals by category                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Create Records                                          │
│     - Create main proclientshow record                      │
│     - Create productshow detail records                     │
│     - Link details to main record                           │
│     - Set audit information                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Display Results                                         │
│     - Show created report                                   │
│     - Display success confirmation                          │
│     - Provide edit/update options                           │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Product Show Update
```
┌─────────────────────────────────────────────────────────────┐
│              START: Update Product Show                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Existing Data                                      │
│     - Load main show record                                 │
│     - Load product detail records                           │
│     - Display current values in form                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Modify Data                                             │
│     - Update client information                             │
│     - Modify product quantities                             │
│     - Adjust prices and totals                              │
│     - Add/remove products as needed                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Recalculate Totals                                      │
│     - Sum updated quantities                                │
│     - Recalculate price totals                              │
│     - Update summary fields                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Save Changes                                            │
│     - Update main record                                    │
│     - Update product detail records                         │
│     - Set update audit fields                               │
│     - Commit all changes                                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display product show creation form |
| `do=add` | `add()` | Process product show creation |
| `do=show` | Show listing | Display all product show records |
| `do=change` | `change()` | Toggle record status |
| `do=edit` | Edit form | Load record for editing |
| `do=update` | `update()` | Process record updates |

### Required Parameters by Action

**Product Show Creation** (`do=add`):
- `client` - Client ID
- `mydate` - Report date
- `alltotal` - Grand total amount
- `allquantity` - Total quantity
- `allquantstore` - Total store quantity
- `pricestore` - Store price total
- `allquantavailable` - Total available quantity
- `priceavailable` - Available price total
- `allquantminus` - Total minus quantity
- `pricestminus` - Minus price total
- `itr` - Number of product iterations

**Product Details** (dynamic):
- `product{N}` - Product ID
- `quantity{N}` - Product quantity
- `prostore{N}` - Store quantity
- `proavailable{N}` - Available quantity
- `prominus{N}` - Minus quantity
- `price{N}` - Product price
- `total{N}` - Line total

**Status Change** (`do=change`):
- `id` - Record ID
- `date` - Status value (1=delete, 0=restore)

**Edit/Update**:
- `id` - Record ID for loading/updating

---

## 🧮 Calculation Methods

### Quantity Calculations
```php
// Multiple quantity states tracked
$allquantity = filter_input(INPUT_POST, 'allquantity');      // Total
$allquantstore = filter_input(INPUT_POST, 'allquantstore');  // In store
$allquantavailable = filter_input(INPUT_POST, 'allquantavailable'); // Available
$allquantminus = filter_input(INPUT_POST, 'allquantminus');  // Shortfall
```

### Price Calculations
```php
// Price totals by quantity type
$pricestore = filter_input(INPUT_POST, 'pricestore');       // Store value
$priceavailable = filter_input(INPUT_POST, 'priceavailable'); // Available value
$pricestminus = filter_input(INPUT_POST, 'pricestminus');   // Minus value
```

### Line Total Calculation
```php
// Individual product totals
$total = filter_input(INPUT_POST, 'total' . $i);
// Presumably: $total = $quantity * $price (calculated on frontend)
```

### Quantity Accumulation (Update)
```php
// Note: This appears to be a bug - should be assignment, not addition
$quantproduct += $quantproduct; // Should be: = $quantproduct
```

---

## 🔒 Security & Permissions

### Authentication Check
```php
include_once("../public/authentication.php");
```

### Input Validation
```php
// All inputs filtered through filter_input()
$client = filter_input(INPUT_POST, 'client');
$mydate = filter_input(INPUT_POST, 'mydate');
// ... etc
```

### DAO Pattern Security
- All database operations through DAO classes
- Parameterized queries prevent SQL injection
- Type checking in DAO layer

### Audit Trail
```php
// Basic audit fields
$datenow = date("Y-m-d");
$userid = $_SESSION["userid"];
$del = 1; // Default active status
```

---

## 📊 Performance Considerations

### Database Optimization
1. **DAO Pattern**: Uses proper data access layer
2. **Foreign Keys**: Proper relationships between tables
3. **Batch Processing**: Product details processed in loops

### Potential Issues
- **Large Product Lists**: Many products may impact form processing time
- **Calculation Complexity**: Multiple quantity states increase complexity
- **Update Bug**: Quantity accumulation logic needs fixing

### Recommended Improvements
```php
// Fix quantity accumulation bug
// Instead of:
$quantproduct += $quantproduct;

// Should be:
$Productshow->quantity = $quantproduct;
```

### Recommended Indexes
```sql
CREATE INDEX idx_proclientshow_client_date ON proclientshow(client, mydate, del);
CREATE INDEX idx_productshow_client_product ON productshow(clientid, productid);
CREATE INDEX idx_proclientshow_userid_date ON proclientshow(userid, datenow);
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Quantity Accumulation Bug**
**Issue**: Product quantities double on update  
**Cause**: Line 345: `$quantproduct += $quantproduct;`

**Fix**:
```php
// Change from:
$quantproduct += $quantproduct;

// To:
$Productshow->quantity = $quantproduct;
```

### 2. **Client Name Not Displaying**
**Issue**: Client names show as IDs in reports  
**Cause**: Client name resolution failing

**Debug**:
```php
foreach ($allclient as $client) {
    $proclient = R::findOne('client', 'clientid = ' . $client->client);
    if (!$proclient) {
        echo "Client not found: " . $client->client;
    }
    $client->proclient = $proclient ? $proclient->clientname : 'Unknown';
}
```

### 3. **Product Details Not Saving**
**Issue**: Product details missing after creation  
**Cause**: Loop iteration or DAO insert issues

**Debug**:
```php
$itr = filter_input(INPUT_POST, 'itr');
echo "Processing $itr product iterations\n";
for ($i = 1; $i <= $itr; $i++) {
    $product = filter_input(INPUT_POST, 'product' . $i);
    if (!$product) {
        echo "Product $i is empty\n";
    }
}
```

### 4. **Status Toggle Not Working**
**Issue**: Change function doesn't update status  
**Cause**: Status value interpretation or DAO update failure

**Debug**:
```php
$name = filter_input(INPUT_POST, 'date');
echo "Status value received: " . $name;
$result = $proclientshowDAO->update($proclientshow);
echo "Update result: " . ($result ? 'success' : 'failed');
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Product Show Creation
```
1. Select client and set date
2. Add multiple products with quantities
3. Verify totals calculate correctly
4. Save and check record creation
5. Verify display in show listing
```

### Test Case 2: Product Show Update
```
1. Load existing product show for editing
2. Modify quantities and prices
3. Add new product to existing show
4. Save changes and verify updates
5. Check quantity accumulation bug
```

### Test Case 3: Status Management
```
1. Create product show record
2. Toggle status to deleted
3. Verify record hidden in normal view
4. Toggle back to active
5. Confirm record reappears
```

### Test Case 4: Client Integration
```
1. Create shows for multiple clients
2. Verify client names display correctly
3. Test with missing client records
4. Check client-specific filtering
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientController.php](#) - Client management
- [productController.php](#) - Product management
- [storedetailController.php](#) - Inventory management
- [Database Schema Documentation](#) - Table relationships

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete (Note: Contains bug in update function)  
**Next Review**: When quantity accumulation bug is fixed