# Product Category Controller Documentation

**File**: `/controllers/productCatController.php`  
**Purpose**: Manages product categories, category hierarchy, units assignment, and category-level pricing and discounts  
**Last Updated**: December 19, 2024  
**Total Functions**: 12  
**Lines of Code**: 883

---

## 📋 Overview

The Product Category Controller is a core component for managing product categorization in the ERP system. It handles hierarchical category structures, category-specific pricing, discount management, and unit assignments.

### Primary Functions
- [x] Create and edit product categories
- [x] Manage category hierarchy (parent-child relationships)
- [x] Assign units to categories
- [x] Set category-level pricing (buy/sell prices)
- [x] Configure category discounts
- [x] Handle temporary and permanent deletion
- [x] Manage optic services settings
- [x] Upload category images/logos
- [x] Batch operations (multiple category actions)
- [x] Menu visibility controls
- [x] Negative sale prevention settings

### Related Controllers
- [productController.php](productController.md) - Product management
- [buyBillController.php](buyBillController.md) - Purchase operations
- [sellbillController.php](sellbillController.md) - Sales operations
- [unitController.php](unitController.md) - Unit management
- [storeController.php](storeController.md) - Store management
- [storedetailController.php](storedetailController.md) - Inventory management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| productcat | Main category table | productCatId, productCatName, productCatParent, conditions |
| productcatunit | Category-unit relationships | productcatunitid, productcatid, unitid, productnumber |

### Related Tables (Referenced)
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| product | Products in categories | Foreign Key: productcat.productCatId |
| unit | Available units | Foreign Key: productcatunit.unitid |
| user | User who created category | Foreign Key: productcat.userId |

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Creates a new product category with all associated settings  
**Called By**: POST request with `do=add`  
**Parameters**:
- `$_POST['productCatName']` (string) - Category name
- `$_POST['productCatDescription']` (string) - Category description
- `$_POST['parent']` (int) - Parent category ID
- `$_POST['inMenu']` (int) - Show in menu (0/1)
- `$_POST['stopNegativeSale']` (int) - Prevent negative sales (0/1)
- `$_POST['discounttype']` (int) - Discount type
- `$_POST['selldiscount']` (float) - Sell discount percentage
- `$_POST['buydiscount']` (float) - Buy discount percentage
- `$_POST['buytotal']` (int) - Buy total setting
- `$_POST['price4']` to `$_POST['price13']` (int) - Additional price levels
- `$_POST['opticServices']` (array) - Optic services
- `$_FILES['logo']` - Category image/logo

**Returns**: int - New category ID

**Database Operations**:
- INSERT into `productcat`
- INSERT into `productcatunit` (for each unit)

**Business Logic Flow**:
```
1. Validate and process form data
   ↓
2. Handle image upload
   ↓
3. Insert category record
   ↓
4. Process category units
   ↓
5. Call online sync function
   ↓
6. Return category ID
```

**Example**:
```php
// Called via POST with category data
$categoryId = add();
```

### 2. show()
**Purpose**: Displays all categories for management interface  
**Called By**: GET request with `do=show`  

**Database Operations**:
- SELECT from `productcat` via `queryAllForShow()`

**Business Logic**:
1. Fetch all categories with extended data
2. Assign to Smarty template
3. Display show.html template

### 3. showByCatId($catId)
**Purpose**: Shows specific category details  
**Parameters**:
- `$catId` (int) - Category ID to display

**Database Operations**:
- SELECT from `productcat` WHERE productCatId = $catId

### 4. executeOperation()
**Purpose**: Performs batch operations on multiple categories  
**Called By**: POST request with `do=executeOperation`  
**Parameters**:
- `$_POST['operation']` (string) - Operation type ("1"=temp delete, "2"=restore)
- `$_POST['choosedItem']` (array) - Array of category IDs

**Business Logic Flow**:
```
1. Get operation type and selected items
   ↓
2. Loop through each selected category
   ↓
3. Perform operation (delete/restore)
   ↓
4. Build result message string
   ↓
5. Display results
```

### 5. tempdelete($productCatid)
**Purpose**: Temporarily deletes a category (soft delete)  
**Parameters**:
- `$productCatid` (int) - Category ID to delete

**Returns**: string - "success" or error message

**Business Logic Flow**:
```
1. Check if category has products
   ↓
2. Check if category has child categories
   ↓
3. If neither exists:
   │  ├─ Set conditions = 1
   │  ├─ Update database
   │  └─ Call online sync
   ↓
4. Return result status
```

**Validation Rules**:
- Cannot delete if products exist in category
- Cannot delete if child categories exist

### 6. returndelete($productCatid)
**Purpose**: Restores a temporarily deleted category  
**Parameters**:
- `$productCatid` (int) - Category ID to restore

**Database Operations**:
- UPDATE `productcat` SET conditions = 0

### 7. edit()
**Purpose**: Loads category data for editing  
**Called By**: GET request with `do=edit&id={categoryId}`  

**Returns**: object - Category data with modified opticServices

**Special Processing**:
- Prepends comma to opticServices for Smarty string position functions

### 8. update()
**Purpose**: Updates existing category with new data  
**Called By**: POST request with `do=update`  
**Parameters**: Same as add() plus:
- `$_POST['productCatId']` (int) - Category ID to update
- `$_POST['conditions']` (int) - Category status

**Business Logic Flow**:
```
1. Load existing category
   ↓
2. Update category properties
   ↓
3. Handle image upload/update
   ↓
4. Delete existing category units
   ↓
5. Insert new category units
   ↓
6. Update database record
```

### 9. deleteFinaly($productCatid)
**Purpose**: Permanently deletes category and all child categories recursively  
**Parameters**:
- `$productCatid` (int) - Category ID to delete permanently

**Business Logic Flow**:
```
1. Get all child categories
   ↓
2. If child categories exist:
   │  ├─ Recursively delete each child
   │  └─ Delete products in category
   ↓
3. Delete category record
   ↓
4. Call online sync
```

**⚠️ Warning**: This is a destructive operation that cannot be undone!

### 10. addCatByNameOnly($catName)
**Purpose**: Quickly creates a category with only a name (used by external apps)  
**Parameters**:
- `$catName` (string) - Category name

**Returns**: int - New category ID

**Use Case**: Used by integrated applications (like obygy) to create basic categories

### 11. getUnits()
**Purpose**: Retrieves all available units for category assignment  
**Returns**: array - All active units

### 12. getProductCatUnits($productCatId)
**Purpose**: Gets all units assigned to a specific category  
**Parameters**:
- `$productCatId` (int) - Category ID

**Returns**: array - Category-unit relationships

---

## 🔄 Business Logic Flow

### Category Creation Workflow
```
┌─────────────────────┐
│ User fills form     │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Validate data       │
│ • Name required     │
│ • Parent valid      │
│ • Prices numeric    │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Process image       │
│ • Upload to server  │
│ • Resize if needed  │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Insert category     │
│ • Main record       │
│ • Unit assignments  │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Online sync         │
│ • Update web store  │
└─────────────────────┘
```

### Category Deletion Safety Check
```
┌─────────────────────┐
│ Delete request      │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Check products      │
│ in category         │
└──────┬──────┬───────┘
       │      │
   Found│      │None
       ▼      ▼
┌───────────┐ ┌─────────────────────┐
│ Block     │ │ Check child         │
│ deletion  │ │ categories          │
└───────────┘ └──────┬──────┬───────┘
                     │      │
                 Found│      │None
                     ▼      ▼
              ┌───────────┐ ┌─────────────┐
              │ Block     │ │ Allow       │
              │ deletion  │ │ deletion    │
              └───────────┘ └─────────────┘
```

---

## ⚠️ Common Issues

### PHP 8.2 Compatibility
**Issue**: Object initialization before property assignment  
**Solution**: Objects are properly initialized in constructor

### Image Upload Handling
**Issue**: File upload errors not properly handled  
**Files**: Uses `uploadImages2()` and `updateImagesWithoutresiz()` functions  
**Solution**: Proper error handling in upload functions

### Recursive Deletion
**Issue**: Stack overflow with deep category hierarchies  
**Solution**: Function handles recursion safely but monitor for very deep trees

### Online Sync Dependency
**Function**: `onlineTempCategoryFunc()`  
**Purpose**: Syncs category changes with web store  
**Issue**: Sync failures can cause inconsistency  

---

## 🔗 Dependencies

### Required Files
```php
include("../public/impOpreation.php");           // Core operations
include("../public/config.php");                // Configuration
include("dailyentryfun.php");                   // Daily entry functions
include("../library/uploadImages.php");         // Image upload functions
```

### DAO Classes
```php
ProductcatDAO.class.php                          // Category operations
ProductDAO.class.php                             // Product operations
ProductcatunitDAO.class.php                      // Category-unit relationships
UnitDAO.class.php                                // Unit operations
ProgramsettingsDAO.class.php                     // System settings
YoutubeLinkDAO.class.php                         // YouTube integration
```

### Views
- `/views/default/productCatview/add.html` - Add category form
- `/views/default/productCatview/edit.html` - Edit category form
- `/views/default/productCatview/show.html` - Category listing
- `/views/default/productCatview/editprint.html` - Print view

### JavaScript Dependencies
- Custom validation scripts for form handling
- Image upload preview functionality
- Dynamic unit row addition/removal

---

## 📊 Performance Considerations

### Database Optimization
- Category hierarchy queries use indexed parent-child relationships
- Bulk operations minimize database calls
- Extended DAO methods provide optimized queries

### Caching Strategy
- Category trees could benefit from caching for large hierarchies
- Unit assignments cached during form display

### Memory Usage
- Recursive deletion loads all children - monitor for large trees
- Image uploads handled efficiently with proper resizing

---

## 🎯 Integration Points

### Web Store Integration
- `onlineTempCategoryFunc()` syncs changes
- Category visibility controlled by `inMenu` setting

### Product Management
- Categories required for product creation
- Category-level pricing affects product defaults

### Inventory Management
- Category units define available measurement types
- Discount settings affect pricing calculations