# Product Category Online Controller Documentation

**File**: `/controllers/productCatOnlineController.php`  
**Purpose**: Manages online store product categories with multilingual support and image handling  
**Last Updated**: December 20, 2024  
**Total Functions**: 8+  
**Lines of Code**: ~338

---

## 📋 Overview

The Product Category Online Controller manages product categories specifically for online store integration. It provides comprehensive CRUD operations with:
- Multilingual support (Arabic & English)
- Image upload and management
- Hierarchical category structure
- Status management (active/inactive)
- AJAX and cURL API support
- Parent-child relationship handling
- Bulk operations support

### Primary Functions
- [x] Add/Edit/Delete online categories
- [x] Multilingual category management
- [x] Image upload and processing
- [x] Parent-child category relationships
- [x] Status toggle functionality
- [x] AJAX/cURL API endpoints
- [x] Hierarchical category display
- [x] YouTube tutorial integration

### Related Controllers
- [productController.php](#) - Product master data
- [onlineStoreController.php](#) - Online store management
- [productCatController.php](#) - Regular product categories

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **onlineproductcat** | Online category master | id, parentid, title, titleEn, description, descriptionEn, image, status, isdel, userid, sysDate |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **user** | System users | userid, username |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Category Form
**Location**: Line 83  
**Purpose**: Display category addition form with parent category options

**Process Flow**:
1. Load parent categories via `getProductCatParents()`
2. Assign categories to template
3. Set custom validation flag
4. Display `onlineproductCatview/add.html`

**Features**:
- Parent category dropdown
- Custom validation
- Clean form interface

---

### 2. **add()** - Create New Category
**Location**: Line 92  
**Purpose**: Insert new online product category with image upload

**Function Signature**:
```php
function add() {
    global $onlineProductCat;
    global $onlineProductCatDAO;
    
    $title = $_POST['title'];
    $titleEn = $_POST['titleEn'];
    $description = $_POST['description'];
    $descriptionEn = $_POST['descriptionEn'];
    $parent = (int) $_POST['parent'];
}
```

**Process Flow**:
1. **Data Extraction**:
   ```php
   $onlineProductCat->parentid = $parent;
   $onlineProductCat->title = $title;
   $onlineProductCat->titleEn = $titleEn;
   $onlineProductCat->description = $description;
   $onlineProductCat->descriptionEn = $descriptionEn;
   $onlineProductCat->sysDate = date("Y-m-d H:i:s");
   $onlineProductCat->userid = $_SESSION['userid'];
   $onlineProductCat->isdel = 0;
   ```

2. **Image Processing**:
   ```php
   $handle = new upload($_FILES['logo']);
   $image = uploadImages2($handle, '../views/default/images/cat_image');
   $onlineProductCat->image = $image;
   ```

3. **Database Insert**:
   ```php
   $productCatId = $onlineProductCatDAO->insert($onlineProductCat);
   ```

**Features**:
- Multilingual title and description
- Parent category assignment (0 for root)
- Image upload with validation
- User tracking
- Soft delete support

---

### 3. **show()** - Display Categories
**Location**: Line 112  
**Purpose**: Show category listing with filtering options

**Process Flow**:
1. Load all non-deleted categories
2. Apply category filter if specified
3. Load YouTube tutorials
4. Call appropriate display function
5. Display via `onlineproductCatview/show.html`

**Filtering Logic**:
```php
$catId = $_REQUEST['catId'];
if (isset($catId) && !empty($catId) && $catId != '-1') {
    showByCatId($catId);
} else {
    show();
}
```

---

### 4. **edit()** - Edit Category Form
**Location**: Line 171  
**Purpose**: Display category edit form with parent options

**Function Signature**:
```php
function edit() {
    global $onlineProductCatDAO;
    
    $productCatid = $_GET['id'];
    $productCatData = $onlineProductCatDAO->load($productCatid);
    return $productCatData;
}
```

**Process Flow**:
1. Get category ID from URL
2. Load parent categories (excluding current category)
3. Load current category data
4. Assign to template variables
5. Display edit form

---

### 5. **update()** - Update Category
**Location**: Line 188  
**Purpose**: Update existing category with new data and image

**Process Flow**:
1. **Load Existing Record**:
   ```php
   $productCatId = $_POST['productCatId'];
   $productCat = $onlineProductCatDAO->load($productCatId);
   ```

2. **Update Fields**:
   ```php
   $productCat->parentid = $parent;
   $productCat->title = $title;
   $productCat->titleEn = $titleEn;
   $productCat->description = $description;
   $productCat->descriptionEn = $descriptionEn;
   $productCat->sysDate = date("Y-m-d H:i:s");
   $productCat->userId = $_SESSION['userid'];
   ```

3. **Image Update**:
   ```php
   $handle = new upload($_FILES['logo']);
   $image = updateImagesWithoutresiz($handle, "oldlogo", '../views/default/images/cat_image');
   $productCat->image = $image;
   ```

4. **Save Changes**:
   ```php
   $onlineProductCatDAO->update($productCat);
   ```

---

### 6. **toggleStatus()** - Status Management
**Location**: Line 147  
**Purpose**: Toggle category active/inactive status

**Process Flow**:
1. Get category ID from URL
2. Load category record
3. Toggle status (0 ↔ 1)
4. Update database
5. Return JSON response for AJAX

**Status Toggle Logic**:
```php
$onlineProductCat = $onlineProductCatDAO->load($id);
if ($onlineProductCat) {
    $onlineProductCat->status = $onlineProductCat->status == 1 ? 0 : 1;
    $onlineProductCatDAO->update($onlineProductCat);
}
```

---

### 7. **deleteFinaly()** - Recursive Deletion
**Location**: Line 326  
**Purpose**: Recursively delete category and all subcategories

**Function Signature**:
```php
function deleteFinaly($productCatid) {
    global $onlineProductCatDAO;
    global $onlineProductCatEX;
}
```

**Recursive Deletion Logic**:
```php
$prodactcatdata = $onlineProductCatEX->queryByParentExt($productCatid);
if (count($prodactcatdata) > 0) {
    foreach ($prodactcatdata as $myprodactcatdata) {
        deleteFinaly($myprodactcatdata->id); // Recursive call
    }
}
$delcatdata = $onlineProductCatDAO->delete($productCatid);
```

---

### 8. **getProductCatParents()** - Parent Category Loading
**Location**: Line 229  
**Purpose**: Load available parent categories excluding current category

**Function Signature**:
```php
function getProductCatParents($productCatid = 0) {
    global $onlineProductCatEX;
    
    $allParents = $onlineProductCatEX->getCategoriesWithoutProducts($productCatid);
    return $allParents;
}
```

---

## 🔄 Workflows

### Workflow 1: Category Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Add New Category                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Form Display                                            │
│     - Load parent categories                                │
│     - Display add form                                      │
│     - Initialize validation                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Data Submission                                         │
│     - Extract multilingual data                             │
│     - Process parent assignment                             │
│     - Handle image upload                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Image Processing                                        │
│     - Validate image upload                                 │
│     - Process and resize                                    │
│     - Save to cat_image directory                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Database Insert                                         │
│     - Set system fields                                     │
│     - Insert category record                                │
│     - Handle success/error response                         │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Hierarchical Deletion
```
┌─────────────────────────────────────────────────────────────┐
│           START: Delete Category Request                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Find Child Categories                                   │
│     - Query categories with parentid = current             │
│     - Build child category list                            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Recursive Processing                                    │
│     FOR EACH child category:                                │
│       │                                                     │
│       ├─→ Call deleteFinaly() recursively                  │
│       │                                                     │
│       └─→ Delete all descendants first                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Delete Current Category                                 │
│     - Remove from database                                  │
│     - Clean up related data                                 │
│     - Return success response                               │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Add category form |
| `do=add` | `add()` | Create new category |
| `do=show` | `show()` | List categories |
| `do=edit` | `edit()` | Edit category form |
| `do=update` | `update()` | Update category |
| `do=deleteFinaly` | `deleteFinaly()` | Delete category and children |
| `do=toggleStatus` | `toggleStatus()` | Toggle active status |
| `do=sucess` | Success page | Operation completed |
| `do=error` | Error page | Operation failed |

### Required Parameters by Action

**Add Category** (`do=add`):
- `title` - Arabic title (required)
- `titleEn` - English title
- `description` - Arabic description
- `descriptionEn` - English description
- `parent` - Parent category ID (0 for root)
- `logo` - Image file upload

**Edit Category** (`do=edit`):
- `id` - Category ID
- `parentid` - Parent category ID (optional)

**Update Category** (`do=update`):
- `productCatId` - Category ID
- All fields from add operation

**Delete Category** (`do=deleteFinaly`):
- `id` - Category ID

**Toggle Status** (`do=toggleStatus`):
- `id` - Category ID

---

## 🧮 Calculation Methods

### Parent Category Assignment
```php
if (empty($parent) || $parent == -1) {
    $parent = 0; // Root category
}
$onlineProductCat->parentid = $parent;
```

### Image Upload Processing
```php
$handle = new upload($_FILES['logo']);
$image = uploadImages2($handle, '../views/default/images/cat_image');
// Returns processed image filename or default on failure
```

### Status Toggle Logic
```php
$newStatus = $currentStatus == 1 ? 0 : 1;
// 0 = Inactive, 1 = Active
```

---

## 🔒 Security & Permissions

### Input Sanitization
```php
$title = $_POST['title'];           // String input
$titleEn = $_POST['titleEn'];       // String input
$parent = (int) $_POST['parent'];   // Integer casting
```

### Image Upload Security
- Uses upload library with validation
- Restricts file types and sizes
- Processes images to standard format
- Saves to controlled directory

### Session Validation
```php
$onlineProductCat->userid = $_SESSION['userid'];
// Tracks user for audit purposes
```

### AJAX/cURL Response Handling
```php
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
    echo json_encode($data);
} else {
    header("location:?do=sucess");
}
```

---

## 📊 Performance Considerations

### Image Processing
- Uses optimized upload library
- Automatic image resizing
- Efficient file handling
- Cleanup of temporary files

### Database Operations
- Single-query operations for CRUD
- Efficient parent-child queries
- Proper indexing on parentid field

### Memory Management
- Minimal object instantiation
- Efficient array processing
- Proper resource cleanup

---

## 🐛 Common Issues & Troubleshooting

### 1. **Image Upload Failures**
**Issue**: Images not uploading or displaying incorrectly  
**Cause**: File permissions or upload directory issues

**Debug Steps**:
```bash
# Check directory permissions
ls -la /Applications/AMPPS/www/erp19/views/default/images/cat_image/

# Verify upload settings
php -i | grep upload
```

### 2. **Parent Category Loops**
**Issue**: Category becomes its own parent  
**Cause**: Improper validation in edit form

**Prevention**:
```php
// Add validation in update function
if ($productCatId == $parent) {
    throw new Exception("Category cannot be its own parent");
}
```

### 3. **Multilingual Data Loss**
**Issue**: Non-English characters corrupted  
**Cause**: Character encoding issues

**Solution**:
```php
// Ensure UTF-8 handling
$title = mb_convert_encoding($_POST['title'], 'UTF-8', 'auto');
```

### 4. **Recursive Deletion Issues**
**Issue**: Deletion fails or leaves orphaned records  
**Cause**: Database constraints or interrupted process

**Debug**:
```sql
-- Check for orphaned categories
SELECT * FROM onlineproductcat 
WHERE parentid NOT IN (SELECT id FROM onlineproductcat WHERE id != parentid)
AND parentid != 0;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Category Operations
```
1. Create root category
2. Create child category
3. Edit both categories
4. Verify parent-child relationship
5. Delete child first, then parent
```

### Test Case 2: Image Upload Testing
```
1. Upload valid image formats (jpg, png, gif)
2. Test invalid formats
3. Test oversized files
4. Verify image processing
5. Test image update scenarios
```

### Test Case 3: Multilingual Support
```
1. Add category with Arabic and English text
2. Verify proper character encoding
3. Test empty English fields
4. Check display in both languages
```

### Test Case 4: Status Management
```
1. Toggle status via AJAX
2. Verify database update
3. Test status inheritance
4. Check UI status indicators
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [productController.md](#) - Product management
- [Image Upload Library Documentation](#) - Upload handling
- [Database Schema Documentation](#) - Table relationships

---

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