# Product Card Controller Documentation

**File**: `/controllers/productcardController.php`  
**Purpose**: Displays detailed product information cards with movement history and pricing  
**Last Updated**: December 20, 2024  
**Total Functions**: 6+  
**Lines of Code**: ~428

---

## 📋 Overview

The Product Card Controller provides comprehensive product information displays including:
- Product movement history
- Pricing information (with permission controls)
- Store-specific or aggregated data
- Size/color variant support
- Historical movement tracking
- User group permission integration

### Primary Functions
- [x] Product information display
- [x] Movement history tracking
- [x] Size/color variant handling
- [x] Store filtering capabilities
- [x] User permission integration
- [x] Price display controls

---

## 🗄️ Database Tables

### Primary Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **storereport** | Product movements | storereportid, productid, storeid, storereportdate, tablename, storereportmodelid |
| **product** | Product master data | productId, productName, productCatId, productBuyPrice, productSellUnitPrice |
| **store** | Store information | storeId, storeName |
| **sizecolorstoredetail** | Size/color variants | sizeid, colorid, productid, storeid, quantity, parcode |
| **usergroup** | User permissions | usergroupid, hideBillPrices, hidecat |

---

## 🔑 Key Functions

### 1. **show()** - Main Product Card Display
**Location**: Line 179  
**Purpose**: Generate comprehensive product information card

**Process Flow**:
1. **Parameter Processing**:
   ```php
   $productId = $_REQUEST['productId'];
   $storeId = $_REQUEST['storeId'];
   $productBuyPrice = $_REQUEST['productBuyPrice'];
   ```

2. **Size/Color Variant Handling**:
   ```php
   if (strpos($productId, "hasSizeColor") !== false) {
       $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
       $productId = $productIdComplex[0];
       $sizeId = $productIdComplex[1];
       $colorId = $productIdComplex[2];
   }
   ```

3. **Product Data Loading**:
   - Store-specific: `loadExtforcard($productId, $storeId)`
   - All stores: `loadExtByProductId2($productId)`

4. **Movement History**:
   ```php
   $storedetailData = $StorereportEX->queryAllqueryString($queryString);
   // Links to source documents based on tablename
   ```

### 2. **Document Linking Logic**
**Location**: Lines 346-367  
**Purpose**: Generate links to source documents for each movement

```php
switch ($detail->tablename) {
    case 'sellbillController.php':
        $detail->link = "sellbillController.php?do=showDetail&sellbillid=" . $detail->storereportmodelid;
        break;
    case 'buyBillController.php':
        $detail->link = "buyBillController.php?do=details&id=" . $detail->storereportmodelid;
        break;
    // ... other cases
}
```

### 3. **Permission-Based Price Display**
**Location**: Lines 278-295  
**Purpose**: Control price visibility based on user group permissions

```php
if (isset($productBuyPrice) && $Usergroupdata->hideBillPrices == 0) {
    $message .= "<br>سعر شراء الصنف : " . $myprodactdata->productBuyPrice;
}
```

---

## 🔄 Workflows

### Workflow: Product Card Generation
```
┌─────────────────────────────────────────┐
│      START: Product Card Request       │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  1. Parameter Analysis                  │
│     - Extract product ID               │
│     - Check for size/color variants    │
│     - Identify store filter            │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  2. Product Data Loading               │
│     - Load basic product info          │
│     - Handle variant information       │
│     - Apply store filtering            │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  3. Movement History                    │
│     - Query movement records           │
│     - Generate document links          │
│     - Calculate summaries              │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  4. Permission Processing              │
│     - Check user group permissions     │
│     - Apply price visibility rules     │
│     - Filter sensitive information     │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│  5. Display Generation                 │
│     - Format message strings           │
│     - Assign template variables        │
│     - Render product card             │
└─────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Description |
|---------------|-------------|
| `do=show` | Display product card |
| `productId` | Product ID (may include size/color: "hasSizeColor-{productId}-{sizeId}-{colorId}") |
| `storeId` | Store filter (-1 for all stores) |
| `from` / `to` | Date range filter |
| `productBuyPrice` | Request buy price display |
| `productSellUnitPrice` | Request unit price display |
| `productSellAllPrice` | Request wholesale price display |
| `productSellHalfPrice` | Request semi-wholesale price display |

---

## 🧮 Calculation Methods

### Size/Color Variant Processing
```php
if (strpos($productId, "hasSizeColor") !== false) {
    $productIdComplex = explode('-', str_replace("hasSizeColor", "", $productId));
    $productId = $productIdComplex[0];
    $sizeId = $productIdComplex[1];
    $colorId = $productIdComplex[2];
    
    $sizeColorStoreDetails = $sizeColorStoreDetailEX->getParcodeByProductSizeAndColorAndStoreEX(
        $productId, $sizeId, $colorId, $storeId
    );
    
    $myprodactdata->productName .= "/$sizeColorStoreDetails->sizeName/$sizeColorStoreDetails->colorName";
    $myprodactdata->parcode = $sizeColorStoreDetails->parcode;
    $myprodactdata->productquantity = $sizeColorStoreDetails->quantity;
}
```

### Movement Query Building
```php
$queryString = ' AND';
if ($productId != '-1') {
    $queryString .= ' storereport.productid = ' . $productId . ' AND';
}
if ($storeId != '-1') {
    $queryString .= ' storereport.storeid = ' . $storeId . ' AND';
}
if ($from != '' && $to != '') {
    $queryString .= ' storereportdate >= "' . $from . '" AND storereportdate <= "' . $to . '" ';
}
```

---

## 🔒 Security & Permissions

### User Group Permission Checks
```php
$Usergroupdata = $UsergroupDAO->load($_SESSION['usergroupid']);

// Price visibility
if ($Usergroupdata->hideBillPrices == 0) {
    // Show pricing information
}

// Category visibility
$smarty->assign('hidecat', $Usergroupdata->hidecat);
```

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

---

## 📊 Performance Considerations

### Optimizations
- Single query for movement history
- Efficient size/color variant handling
- Proper query string building with cleanup

### Potential Issues
- Complex product ID parsing for variants
- Multiple conditional queries based on store selection
- Large movement history could impact performance

---

## 🐛 Common Issues & Troubleshooting

### 1. **Size/Color Variant Issues**
**Issue**: Variant information not displaying correctly
**Cause**: Improper parsing of complex product IDs

**Debug**:
```php
// Check for proper variant format
if (strpos($productId, "hasSizeColor") !== false) {
    error_log("Variant detected: " . $productId);
    // Verify parsing logic
}
```

### 2. **Permission Conflicts**
**Issue**: Prices showing for restricted users
**Cause**: User group permissions not properly loaded

**Fix**:
```sql
-- Verify user group settings
SELECT u.userid, ug.hideBillPrices 
FROM user u 
JOIN usergroup ug ON u.usergroupid = ug.usergroupid 
WHERE u.userid = ?;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Product Card
```
1. Load product card for simple product
2. Verify basic information display
3. Check movement history
4. Test document links
```

### Test Case 2: Size/Color Variants
```
1. Load variant product with size/color
2. Verify variant information parsing
3. Check quantity calculations
4. Test variant-specific data
```

### Test Case 3: Permission Testing
```
1. Test with different user groups
2. Verify price visibility rules
3. Check category access permissions
4. Test store filtering restrictions
```

---

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