# Unit Controller Documentation

**File**: `/controllers/unitController.php`  
**Purpose**: Manages units of measurement for products and categories  
**Last Updated**: December 19, 2024  
**Total Functions**: 8  
**Lines of Code**: 311

---

## 📋 Overview

The Unit Controller manages all units of measurement used throughout the ERP system. Units are fundamental building blocks that define how products are measured (pieces, kilograms, liters, etc.) and are essential for inventory management, billing, and reporting.

### Primary Functions
- [x] Create new measurement units
- [x] Edit existing units
- [x] Display all units in management interface
- [x] Soft delete units (temporary removal)
- [x] Restore deleted units
- [x] Batch operations on multiple units
- [x] Validate unit dependencies before deletion
- [x] Integration with product-category unit assignments

### Related Controllers
- [productCatController.php](productCatController.md) - Category-unit assignments
- [productController.php](productController.md) - Product unit assignments
- [buyBillController.php](buyBillController.md) - Purchase quantities
- [sellbillController.php](sellbillController.md) - Sales quantities
- [storedetailController.php](storedetailController.md) - Inventory quantities
- [inventoryController.php](#) - Stock management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| unit | Main units table | unitId, unitName, unitSymbol, unitDescription, conditions |

### Related Tables (Referenced)
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| productunit | Product-unit assignments | Foreign Key: unit.unitId |
| productcatunit | Category-unit assignments | Foreign Key: unit.unitId |
| buybilldetail | Purchase quantities | Foreign Key: unit.unitId |
| sellbilldetail | Sales quantities | Foreign Key: unit.unitId |
| storedetail | Inventory quantities | Foreign Key: unit.unitId |

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Creates a new unit of measurement  
**Called By**: POST request with `do=add`  
**Parameters**:
- `$_POST['unitName']` (string) - Unit name (e.g., "Kilogram", "Piece")
- `$_POST['unitSymbol']` (string) - Unit symbol (e.g., "kg", "pcs")
- `$_POST['unitDescription']` (string) - Optional description

**Returns**: void (redirects on success/error)

**Database Operations**:
- INSERT into `unit` table

**Business Logic**:
1. Collect form data
2. Set default conditions = 0 (active)
3. Set current date
4. Set current user ID
5. Insert unit record

**Example**:
```php
// POST data: unitName="Kilogram", unitSymbol="kg", unitDescription="Weight unit"
add(); // Creates new unit and redirects
```

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

**Database Operations**:
- SELECT * FROM `unit` via `queryAll()`

**Business Logic**:
1. Fetch all unit records
2. Assign to Smarty template variable
3. Display in show.html template

**Template Integration**:
- Displays units in table format
- Shows unit name, symbol, description
- Provides edit/delete action buttons

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

**Returns**: void (displays results)

**Business Logic Flow**:
```
1. Get operation type and selected units
   ↓
2. Loop through each unit ID
   ↓
3. Load unit data for name display
   ↓
4. Perform operation:
   │  ├─ Type "1": Call tempdelete()
   │  └─ Type "2": Call returndelete()
   ↓
5. Build result message string
   ↓
6. Display results to user
```

**Output Format**:
- Success: "Unit Name: Operation completed successfully"
- Error: "Unit Name: Error message"

### 4. tempdelete($unitid)
**Purpose**: Safely deletes a unit with dependency validation  
**Parameters**:
- `$unitid` (int) - Unit ID to delete

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

**Business Logic Flow**:
```
┌─────────────────────┐
│ Receive unit ID     │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Check dependencies  │
│ Query productunit   │
│ table for usage     │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Dependencies?       │
└─────┬─────────┬─────┘
      │         │
    Yes│         │No
      ▼         ▼
┌───────────┐ ┌─────────────────────┐
│ Return    │ │ Set conditions = 1  │
│ error     │ │ (soft delete)       │
│ message   │ │                     │
└───────────┘ └─────────────────────┘
```

**Validation Rules**:
- Cannot delete if used in product-unit assignments
- Returns specific error message for blocked deletions

**Error Messages**:
- Arabic: "لا يمكن حذف هذه الوحدة لارتباطها بمنتجات"
- Translation: "Cannot delete this unit because it's linked to products"

### 5. returndelete($unitid)
**Purpose**: Restores a temporarily deleted unit  
**Parameters**:
- `$unitid` (int) - Unit ID to restore

**Database Operations**:
- UPDATE `unit` SET conditions = 0 WHERE unitId = $unitid

**Business Logic**:
1. Restore unit by setting conditions back to 0
2. Unit becomes available for use again

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

**Returns**: object - Unit data for form population

**Database Operations**:
- SELECT * FROM `unit` WHERE unitId = $unitId

**Template Integration**:
- Populates edit form with existing data
- Allows modification of name, symbol, description

### 7. update()
**Purpose**: Updates existing unit with new data  
**Called By**: POST request with `do=update`  
**Parameters**:
- `$_POST['unitId']` (int) - Unit ID to update
- `$_POST['unitName']` (string) - Updated unit name
- `$_POST['unitSymbol']` (string) - Updated symbol
- `$_POST['unitDescription']` (string) - Updated description
- `$_POST['conditions']` (int) - Unit status (0=active, 1=deleted)

**Database Operations**:
- UPDATE `unit` SET ... WHERE unitId = $unitId

**Business Logic**:
1. Collect form data
2. Set current date and user ID
3. Update all unit properties
4. Preserve unit ID for update

### 8. Global Helper Functions
**Purpose**: Utility functions used throughout the system

**getUnits()** (referenced in other controllers):
- Returns all active units for dropdowns
- Used in product and category management

---

## 🔄 Business Logic Flow

### Unit Creation Workflow
```
┌─────────────────────┐
│ User fills form     │
│ • Name (required)   │
│ • Symbol (optional) │
│ • Description       │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Server validation   │
│ • Check required    │
│   fields            │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Insert to database  │
│ • Set conditions=0  │
│ • Set current date  │
│ • Set user ID       │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Redirect to success │
└─────────────────────┘
```

### Unit Deletion Safety Check
```
┌─────────────────────┐
│ Delete request      │
│ for unit ID         │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Query productunit   │
│ WHERE unitid = ID   │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│ Found records?      │
└─────┬─────────┬─────┘
      │         │
    Yes│         │No
      ▼         ▼
┌───────────┐ ┌─────────────────────┐
│ Block     │ │ Allow deletion:     │
│ deletion  │ │ SET conditions = 1  │
│ Return    │ │ Return "success"    │
│ error     │ │                     │
└───────────┘ └─────────────────────┘
```

---

## ⚠️ Common Issues

### Dependency Validation
**Issue**: Attempting to delete units that are in use  
**Solution**: System checks `productunit` table before allowing deletion  
**Error Handling**: Returns descriptive Arabic error message

### Unicode Support
**Issue**: Arabic unit names and symbols need proper encoding  
**Solution**: Database and forms configured for UTF-8 support

### Symbol Standardization
**Issue**: Inconsistent unit symbols  
**Best Practice**: Use standard abbreviations (kg, pcs, L, m², etc.)

---

## 🔗 Dependencies

### Required Files
```php
include("../public/impOpreation.php");           // Core operations
include("../public/config.php");                // Configuration
include("../public/authentication.php");        // User authentication
```

### DAO Classes
```php
UnitDAO.class.php                               // Basic unit operations
UnitMySqlExtDAO.class.php                       // Extended unit operations
ProductunitDAO.class.php                        // Product-unit relationships
YoutubeLinkDAO.class.php                        // YouTube integration (help videos)
```

### Views
- `/views/default/unitview/add.html` - Add unit form
- `/views/default/unitview/edit.html` - Edit unit form
- `/views/default/unitview/show.html` - Units listing
- `/views/default/unitview/editprint.html` - Print view

### Global Variables
```php
$unit                                           // Unit DTO object
$unitDAO                                        // Unit DAO object
$unitExt                                        // Extended DAO object
$productUnitDAO                                 // Product-unit relationships
$today                                          // Current date
```

---

## 📊 Performance Considerations

### Database Queries
- Simple CRUD operations with minimal joins
- Index on unitId for fast lookups
- Dependency checks use efficient count queries

### Memory Usage
- Lightweight controller with small data sets
- Units table typically contains <100 records

### Caching Opportunities
- Unit list could be cached for dropdown menus
- Rarely changes, good candidate for application-level caching

---

## 🎯 Integration Points

### Product Management
- Units assigned to products for quantity measurement
- Default unit inheritance from category settings

### Inventory System
- All stock quantities tracked with units
- Conversion between units handled by related controllers

### Billing System
- Purchase and sales quantities use unit measurements
- Unit symbols displayed on bills and invoices

### Reporting
- Inventory reports group by units
- Sales reports show quantities with proper unit labels

---

## 📋 Usage Examples

### Common Unit Types
```php
// Weight units
Name: "Kilogram", Symbol: "kg"
Name: "Gram", Symbol: "g"
Name: "Ton", Symbol: "t"

// Count units
Name: "Piece", Symbol: "pcs"
Name: "Dozen", Symbol: "dz"
Name: "Box", Symbol: "box"

// Volume units
Name: "Liter", Symbol: "L"
Name: "Milliliter", Symbol: "mL"
Name: "Cubic Meter", Symbol: "m³"

// Length units
Name: "Meter", Symbol: "m"
Name: "Centimeter", Symbol: "cm"
Name: "Kilometer", Symbol: "km"
```

### Typical Workflow
1. Administrator creates standard units (kg, pcs, L, etc.)
2. Categories are assigned appropriate units
3. Products inherit units from categories or override
4. Purchase/sales use these units for quantities
5. Reports display quantities with proper unit symbols

---

## 🔍 Troubleshooting

### Cannot Delete Unit
**Symptom**: Unit deletion fails with Arabic error message  
**Cause**: Unit is assigned to one or more products  
**Solution**: 
1. Remove unit from all products first
2. Or use temporary deletion to hide unit

### Missing Units in Dropdowns
**Symptom**: Units not appearing in product/category forms  
**Cause**: Units marked as deleted (conditions = 1)  
**Solution**: Restore units using returndelete function

### Character Encoding Issues
**Symptom**: Arabic text not displaying correctly  
**Cause**: Database charset or page encoding mismatch  
**Solution**: Ensure UTF-8 encoding throughout the system