# Currency Controller Documentation

**File**: `/controllers/currencyController.php`  
**Purpose**: Manages multi-currency support, exchange rates, and currency conversion settings  
**Last Updated**: December 19, 2024  
**Total Functions**: 5  
**Lines of Code**: 201

---

## 📋 Overview

The Currency Controller manages the multi-currency functionality in the ERP system. It handles:
- Creating and managing different currencies
- Setting conversion factors and exchange rates
- Primary currency management
- Currency symbols and display formats
- Soft deletion of unused currencies
- Integration with program settings for main currency

### Primary Functions
- [x] Add new currencies with conversion rates
- [x] View all active currencies in listing
- [x] Edit existing currency information
- [x] Update currency conversion factors
- [x] Soft delete (deactivate) currencies
- [x] Special handling for primary currency updates
- [x] Program settings integration

### Related Controllers
- [programsettingsController.md](programsettingsController.md) - Main currency settings
- [sellbillController.md](sellbillController.md) - Multi-currency sales
- [buyBillController.md](buyBillController.md) - Multi-currency purchases
- [supplierController.md](supplierController.md) - Supplier currency preferences
- [clientController.md](clientController.md) - Customer currency preferences
- [balancereportController.md](balancereportController.md) - Currency conversion in reports
- [accountstree.md](accountstree.md) - Account currency settings
- [dailyentry.md](dailyentry.md) - Multi-currency accounting entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **currency** | Currency definitions | id, name, symbol, conversionFactor, otherconversionFactor, conditions, userid, sysDate |

### Related Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **programsettings** | System main currency | programsettings.currancy linked to currency.name |
| **buybillcurr** | Purchase currency details | References currency.id |
| **sellbillcurr** | Sales currency details | References currency.id |
| **youtubelink** | Associated help content | General system integration |

### Currency Fields Structure
| Column | Type | Purpose | Notes |
|--------|------|---------|-------|
| **id** | int | Primary key | Auto-increment |
| **name** | varchar | Currency name | e.g., "US Dollar", "Euro" |
| **symbol** | varchar | Currency symbol | e.g., "$", "€", "£" |
| **conversionFactor** | decimal | Rate to main currency | Main currency = 1.0 |
| **otherconversionFactor** | decimal | Alternative rate | For complex conversions |
| **conditions** | int | Status flag | 0=active, 1=deleted |
| **userid** | int | User who created/modified | Foreign key to user table |
| **sysDate** | datetime | Last modification timestamp | Auto-updated |

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Create a new currency with conversion factors  
**Called By**: Form submission with `?do=add`  
**Line**: 132

**Parameters** (via $_POST):
- `name` (string) - Currency name (e.g., "US Dollar")
- `symbol` (string) - Currency symbol (e.g., "$")
- `conversionFactor` (float) - Exchange rate to main currency
- `othercFactor` (float) - Alternative conversion factor

**Process Flow**:
```
Form Data Collection
         ↓
Input Validation & Filtering
         ↓
Currency Object Creation
         ↓
Set Default Properties
         ↓
Database Insert
         ↓
Redirect to Success
```

**Business Logic**:
1. Filters and validates input using `filter_input()`
2. Creates currency object with automatic properties:
   - `conditions = 0` (active status)
   - `userid` from current session
   - `sysDate` as current timestamp
3. Inserts into database via CurrencyDAO

**Code Example**:
```php
$currency->name = $name;
$currency->symbol = $symbol;
$currency->conversionFactor = $conversionFactor;
$currency->otherconversionFactor = $otherconversionFactor;
$currency->conditions = 0; // Active
$currency->userid = $_SESSION['userid'];
$currency->sysDate = date('Y-m-d H:i:s');
```

### 2. show()
**Purpose**: Display all active currencies in listing format  
**Called By**: Navigation to `?do=show`  
**Line**: 153

**Database Query**: `$currencyDAO->queryByConditions(0)` - Only active currencies

**Process Flow**:
```
Query Active Currencies (conditions=0)
         ↓
Assign to Smarty Template
         ↓
Display Currency Listing
         ↓
Include YouTube Links for Help
```

**Business Logic**:
1. Queries only active currencies (conditions = 0)
2. Excludes soft-deleted currencies
3. Integrates help content via YouTube links
4. Assigns data to template for display

### 3. edit()
**Purpose**: Load currency data for editing form  
**Called By**: Edit action with `?do=edit&id=X`  
**Line**: 161

**Parameters** (via $_GET):
- `id` (int) - Currency ID to edit

**Return Value**: Currency object with all current data

**Process Flow**:
```
Get Currency ID from URL
         ↓
Validate ID (integer cast)
         ↓
Load Currency from Database
         ↓
Return Currency Object
         ↓
Populate Edit Form
```

**Business Logic**:
1. Safely casts ID to integer for security
2. Loads complete currency record
3. Returns object for form population

### 4. update()
**Purpose**: Update existing currency information with special main currency handling  
**Called By**: Form submission with `?do=update`  
**Line**: 169

**Parameters** (via $_POST):
- `id` (int) - Currency ID to update
- `name` (string) - Updated currency name
- `symbol` (string) - Updated currency symbol
- `conversionFactor` (float) - Updated exchange rate
- `othercFactor` (float) - Updated alternative rate

**Process Flow**:
```
Load Existing Currency
         ↓
Update Currency Properties
         ↓
Database Update
         ↓
┌─────────────────┐
│ Check if ID = 1 │ (Main Currency)
└─────────────────┘
         ↓
Update Program Settings
         ↓
Redirect to Success
```

**Business Logic**:
1. Loads existing currency to preserve system fields
2. Updates modifiable fields with new values
3. Updates timestamp and user who modified
4. **Special Case**: If currency ID = 1 (main currency):
   - Updates `programsettings.currancy` field
   - Keeps system-wide currency name in sync

**Main Currency Update Code**:
```php
if ($id == 1) {
    $ProgramsettingEX->runSqlQuery(
        "UPDATE programsettings SET currancy = '" . $currency->name . "' WHERE programsettingsid=1"
    );
}
```

### 5. delete()
**Purpose**: Soft delete currency (mark as inactive)  
**Called By**: Delete action with `?do=delete&id=X`  
**Line**: 193

**Parameters** (via $_GET):
- `id` (int) - Currency ID to delete

**Process Flow**:
```
Get Currency ID
         ↓
Load Currency Record
         ↓
Set conditions = 1 (deleted)
         ↓
Update Database
         ↓
Currency Hidden from Lists
```

**Business Logic**:
1. Implements **soft delete** - doesn't remove from database
2. Sets `conditions = 1` to mark as deleted
3. Preserves data integrity for historical transactions
4. Currency becomes invisible in active listings

**Why Soft Delete**:
- Historical bills may reference this currency
- Conversion calculations remain valid
- Audit trail preserved
- Can be reactivated if needed

---

## 🔄 Business Logic Flow

### Currency Creation Workflow
```
New Currency Form Entry
         ↓
┌─────────────────────────┐
│ Validate Input Data     │
│ - Name not empty        │
│ - Symbol format         │
│ - Conversion factor > 0 │
└─────────────────────────┘
         ↓
┌─────────────────────────┐
│ Create Currency Object  │
│ - Set active status     │
│ - Set current user      │
│ - Set current datetime  │
└─────────────────────────┘
         ↓
┌─────────────────────────┐
│ Insert to Database      │
│ - Generate currency ID  │
│ - Save all properties   │
└─────────────────────────┘
         ↓
Currency Available for Use
```

### Main Currency Update Workflow
```
Currency Update Request
         ↓
┌──────────────────────────┐
│ Load Currency Record     │
│ - Validate exists        │
│ - Get current values     │
└──────────────────────────┘
         ↓
┌──────────────────────────┐
│ Update Currency Fields   │
│ - Name, symbol, rates    │
│ - User and timestamp     │
└──────────────────────────┘
         ↓
┌──────────────────────────┐
│ Check if Main Currency   │
│ (currency_id = 1)        │
└──────────────────────────┘
         ↓
    Is Main Currency?
         ↓              ↓
      YES              NO
         ↓              ↓
┌────────────────┐  ┌─────────────┐
│ Update Program │  │ Update Only │
│ Settings Table │  │ Currency    │
│ - currancy =   │  │ Record      │
│   new name     │  └─────────────┘
└────────────────┘       ↓
         ↓              ↓
         └─────────────┘
                 ↓
         Update Complete
```

### Currency Conversion Process
```
Transaction with Foreign Currency
            ↓
┌─────────────────────────────┐
│ Get Transaction Currency    │
│ - Load currency record      │
│ - Get conversion factor     │
└─────────────────────────────┘
            ↓
┌─────────────────────────────┐
│ Apply Conversion            │
│ Foreign Amount ÷ Factor =   │
│ Main Currency Amount        │
└─────────────────────────────┘
            ↓
┌─────────────────────────────┐
│ Store Both Values           │
│ - Original currency amount  │
│ - Converted amount          │
│ - Exchange rate used        │
└─────────────────────────────┘
            ↓
    Transaction Recorded
```

---

## ⚠️ Common Issues

### 1. **Main Currency Synchronization**
**Symptoms**: Currency name mismatch between currency table and program settings  
**Causes**: Direct database edits or failed updates

**Solutions**:
- Always update main currency through controller
- Check programsettings.currancy matches currency.name where id=1
- Run synchronization query if needed:
```sql
UPDATE programsettings SET currancy = (
    SELECT name FROM currency WHERE id = 1
) WHERE programsettingsid = 1;
```

### 2. **Conversion Factor Errors**
**Symptoms**: Incorrect currency calculations in bills  
**Causes**: 
- Zero or negative conversion factors
- Inverted conversion rates
- Missing conversion factors

**Solutions**:
- Validate conversion factor > 0 before saving
- Document conversion direction clearly
- Test calculations with known amounts

### 3. **Orphaned Currency References**
**Symptoms**: Bills showing "unknown currency" or errors  
**Causes**: Currency soft-deleted but still referenced in old bills

**Solutions**:
- Check bill dependencies before deletion
- Consider archiving instead of deletion
- Implement cascade handling for dependent records

### 4. **Performance Issues with Currency Lookups**
**Symptoms**: Slow loading of bills with multiple currencies  
**Causes**: Frequent currency table queries without optimization

**Solutions**:
- Cache frequently used currency data
- Use JOIN queries instead of multiple lookups
- Index currency table properly

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core system operations
- `../public/config.php` - Database configuration
- `../public/include_dao.php` - Data access layer includes

### Required DAOs
- `CurrencyDAO.class.php` - Currency data access interface
- `Currency.class.php` - Currency data transfer object
- `CurrencyMySqlDAO.class.php` - MySQL currency operations
- `CurrencyMySqlExtDAO.class.php` - Extended currency operations
- `ProgramsettingsDAO.class.php` - Program settings access
- `Programsetting.class.php` - Settings DTO
- `ProgramsettingsMySqlDAO.class.php` - Settings MySQL operations
- `ProgramsettingsMySqlExtDAO.class.php` - Extended settings operations

### Template Files
- `currencyview/add.html` - Currency creation form
- `currencyview/show.html` - Currency listing display
- `currencyview/edit.html` - Currency editing form
- `header.html` - Standard page header
- `footer.html` - Standard page footer
- `succes.html` - Success message template
- `error.html` - Error message template

### Integration Dependencies
- **Program Settings**: Main currency name synchronization
- **Bill Controllers**: Multi-currency transaction support
- **Report Controllers**: Currency conversion for reporting
- **Client/Supplier Controllers**: Preferred currency settings

---

## 🎯 Usage Examples

### Adding a New Currency
```php
// Form data for adding Euro
$_POST = [
    'name' => 'Euro',
    'symbol' => '€',
    'conversionFactor' => 0.85,  // 1 USD = 0.85 EUR
    'othercFactor' => 1.18       // 1 EUR = 1.18 USD
];
```

### Conversion Calculation Example
```php
// If main currency is USD and rate is 0.85 EUR per USD
$usd_amount = 100.00;
$eur_rate = 0.85;
$eur_amount = $usd_amount * $eur_rate; // 85.00 EUR
```

### Main Currency Check
```php
// Always check if updating main currency
if ($currency_id == 1) {
    // Update both currency table and program settings
    // This ensures system-wide consistency
}
```

---

## 💡 Best Practices

### Currency Management
1. **Always validate conversion factors** before saving
2. **Test currency calculations** with known amounts
3. **Document conversion direction** clearly
4. **Use soft delete** to preserve historical data
5. **Keep main currency in sync** with program settings

### Performance Optimization
1. **Cache currency data** for frequent lookups
2. **Index currency queries** for better performance
3. **Use batch operations** for bulk currency updates
4. **Monitor conversion calculations** for accuracy

### Data Integrity
1. **Check dependencies** before deleting currencies
2. **Validate historical references** remain intact
3. **Backup before major changes** to currency settings
4. **Test multi-currency scenarios** thoroughly