# Multi-Currency System Guide

## Overview

The chocolate ordering system now supports **multi-currency pricing** with automatic conversion. This allows you to:
- Enter costs in different currencies (EUR, USD, GBP, RON, etc.)
- **Display prices to customers in Romanian Lei (RON)** automatically
- Use a built-in currency converter
- Manage exchange rates

## 🎯 Key Feature: Customers See Prices in LEI

**By default, all customers will see product prices in Romanian Lei (RON)**, even though you manage costs in EUR internally. The system automatically converts EUR prices to RON using real-time exchange rates.

---

## Supported Currencies

The system supports the following currencies:

| Code | Name | Symbol | Current Rate (vs EUR) |
|------|------|--------|---------------------|
| EUR | Euro | € | 1.0000 (base) |
| RON | Romanian Leu | RON | 4.9700 |
| USD | US Dollar | $ | 1.0900 |
| GBP | British Pound | £ | 0.8600 |
| CHF | Swiss Franc | CHF | 0.9400 |
| PLN | Polish Złoty | PLN | 4.3200 |
| HUF | Hungarian Forint | HUF | 397.5000 |

**Note**: Exchange rates are configured in the system and can be updated as needed.

---

## How It Works

### 1. **Admin Side (Backend - EUR)**
- Add products with costs in EUR
- Set purchase costs, transport costs, processing costs in EUR
- Calculate markup and final price in EUR

### 2. **Customer Side (Frontend - RON)**
- All product prices automatically converted from EUR to RON
- Display format: `24.85 RON` (using Romanian number format)
- Shopping cart totals shown in RON
- Order history shows RON prices

### 3. **Conversion Formula**
```
Price in RON = Price in EUR × 4.97 (current EUR→RON rate)
```

Example:
- Product cost in EUR: €5.00
- Customer sees: **24.85 RON**

---

## Using the Currency Tab (Admin)

### Access Currency Settings
1. Login as admin: http://localhost:3000
2. Click on the **"Currency"** tab
3. You'll see three sections:
   - Quick Currency Converter
   - Currency Settings for Costs
   - Current Exchange Rates

### Currency Settings for Costs

Configure which currency to use for different cost types:

| Setting | Purpose | Recommended |
|---------|---------|-------------|
| **Purchase Cost Currency** | Currency used when entering product purchase costs | EUR |
| **Transport Cost Currency** | Currency for shipping/transport costs | EUR |
| **Processing Cost Currency** | Currency for processing/handling costs | EUR |
| **Customer Display Currency** | Currency shown to customers | **RON** ✅ |

**Example Configuration:**
```
Purchase Cost: EUR
Transport Cost: EUR
Processing Cost: EUR
Customer Display: RON (customers see prices in Lei)
```

Click **"Save Currency Settings"** to apply changes.

---

## Using the Currency Converter

### Quick Converter
1. Click **"Open Converter"** button in the Currency tab
2. Enter an amount (e.g., 100)
3. Select "From Currency" (e.g., EUR)
4. Select "To Currency" (e.g., RON)
5. See instant conversion: `100.00 € = 497.00 RON`

The converter updates in real-time as you change values.

### Common Conversions

**EUR to RON:**
- 1 EUR = 4.97 RON
- 10 EUR = 49.70 RON
- 100 EUR = 497.00 RON

**RON to EUR:**
- 1 RON = 0.20 EUR
- 50 RON = 10.06 EUR
- 500 RON = 100.60 EUR

---

## API Endpoints

The system provides REST API endpoints for currency operations:

### GET /api/currency/currencies
Get list of all supported currencies
```json
{
  "currencies": {
    "EUR": { "symbol": "€", "name": "Euro" },
    "RON": { "symbol": "RON", "name": "Romanian Leu" }
  }
}
```

### GET /api/currency/rates
Get current exchange rates
```json
{
  "rates": {
    "EUR": 1.0,
    "RON": 4.97,
    "USD": 1.09
  },
  "baseCurrency": "EUR"
}
```

### POST /api/currency/convert
Convert amount between currencies
```json
{
  "amount": 100,
  "from": "EUR",
  "to": "RON"
}
```

Response:
```json
{
  "original": {
    "amount": 100,
    "currency": "EUR",
    "symbol": "€"
  },
  "converted": {
    "amount": 497,
    "currency": "RON",
    "symbol": "RON"
  },
  "rate": 4.97
}
```

### GET /api/currency/batch-settings
Get current currency settings
```json
{
  "purchase_currency": "EUR",
  "transport_currency": "EUR",
  "processing_currency": "EUR",
  "display_currency": "RON"
}
```

### POST /api/currency/batch-settings
Update currency settings (admin only)
```json
{
  "purchase_currency": "EUR",
  "transport_currency": "EUR",
  "processing_currency": "EUR",
  "display_currency": "RON"
}
```

---

## JavaScript Usage

The `CurrencyConverter` module is available globally in both admin and customer portals.

### Initialize Currency System
```javascript
// Automatically initialized on page load
await CurrencyConverter.init();
```

### Convert Currency
```javascript
// Convert 100 EUR to RON
const amountInRON = CurrencyConverter.convert(100, 'EUR', 'RON');
console.log(amountInRON); // 497.00

// Convert to display currency (default RON)
const displayPrice = CurrencyConverter.toDisplayCurrency(5.00, 'EUR');
console.log(displayPrice); // 24.85
```

### Format Currency
```javascript
// Format amount with currency symbol
const formatted = CurrencyConverter.format(497.00, 'RON');
console.log(formatted); // "497.00 RON"

const formatted2 = CurrencyConverter.format(100, 'EUR');
console.log(formatted2); // "€100.00"
```

### Get Exchange Rate
```javascript
// Get current rate between two currencies
const rate = CurrencyConverter.getRate('EUR', 'RON');
console.log(rate); // 4.97
```

---

## Customer Portal Pricing Display

### Product Grid
```javascript
// Product prices automatically converted to RON
products.map(product => {
    const priceInRON = CurrencyConverter.toDisplayCurrency(product.final_price, 'EUR');
    return `
        <div class="product-card">
            <h3>${product.name}</h3>
            <div class="price">${CurrencyConverter.format(priceInRON, 'RON')}</div>
        </div>
    `;
});
```

**Result**: Customer sees `24.85 RON` instead of `€5.00`

### Shopping Cart
```javascript
// Cart items show prices in RON
const priceInRON = CurrencyConverter.toDisplayCurrency(item.product.final_price, 'EUR');
const subtotal = priceInRON * item.quantity;

// Display: "Price: 24.85 RON each"
// Display: "Subtotal: 248.50 RON"
```

### Cart Total
```javascript
// Total converted from EUR to RON
const totalInEUR = cart.reduce((sum, item) => sum + (item.product.final_price * item.quantity), 0);
const totalInRON = CurrencyConverter.toDisplayCurrency(totalInEUR, 'EUR');

// Display: "Total: 2,485.00 RON"
```

---

## Database Schema

### currency_settings Table
```sql
CREATE TABLE currency_settings (
    id INTEGER PRIMARY KEY DEFAULT 1,
    purchase_currency TEXT DEFAULT 'EUR',
    transport_currency TEXT DEFAULT 'EUR',
    processing_currency TEXT DEFAULT 'EUR',
    display_currency TEXT DEFAULT 'RON',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

**Default Settings:**
- Purchase/Transport/Processing: **EUR**
- Customer Display: **RON**

---

## Price Calculation Workflow

### Step 1: Admin Adds Product in EUR
```
Purchase Cost: €3.00
Processing Cost: €0.50
Transport Cost: €0.50
Markup: 30%
Final Price (EUR): €5.20
```

### Step 2: System Stores in EUR
```sql
INSERT INTO products (base_purchase_cost, processing_cost, allocated_transport_cost, final_price)
VALUES (3.00, 0.50, 0.50, 5.20);
```

### Step 3: Customer Views in RON
```
Final Price (EUR): €5.20
Conversion: 5.20 × 4.97 = 25.84
Customer Sees: 25.84 RON
```

---

## Updating Exchange Rates

### Manual Update (Current System)
Exchange rates are hardcoded in [routes/currency.js](routes/currency.js:11-19):

```javascript
let exchangeRates = {
    EUR: 1.0,
    USD: 1.09,
    GBP: 0.86,
    RON: 4.97,  // ← Update this value
    CHF: 0.94,
    PLN: 4.32,
    HUF: 397.50
};
```

**To update rates:**
1. Edit `routes/currency.js`
2. Update the rate values
3. Restart the server

### Future: Automatic Updates
In production, you can integrate with exchange rate APIs:
- https://exchangerate-api.com
- https://openexchangerates.org
- European Central Bank API

---

## Troubleshooting

### Issue: Customers see EUR instead of RON
**Solution**: Check currency settings in the Currency tab. Ensure "Customer Display Currency" is set to **RON**.

### Issue: Wrong conversion rate
**Solution**: Check the exchange rate in `routes/currency.js`. The current EUR→RON rate should be approximately 4.97.

### Issue: Prices not converting
**Solution**:
1. Open browser console (F12)
2. Check for JavaScript errors
3. Ensure `currency.js` is loaded before `customer.js`

### Issue: Currency converter not opening
**Solution**: Check that `CurrencyConverter.init()` has completed. The converter needs rates to be loaded first.

---

## Examples

### Example 1: Add Product with EUR Costs
```
1. Login as admin
2. Go to Products → Add Product
3. Enter costs in EUR:
   - Purchase Cost: €4.00
   - Transport: €0.30
   - Processing: €0.20
   - Markup: 30%
4. Save product
5. Customer sees: 23.73 RON
```

**Calculation:**
- Total Cost: €4.00 + €0.30 + €0.20 = €4.50
- With 30% markup: €4.50 × 1.30 = €5.85
- In RON: €5.85 × 4.97 = 29.07 RON

### Example 2: Use Currency Converter
```
1. Go to Admin → Currency tab
2. Click "Open Converter"
3. Enter: 50 EUR
4. From: EUR
5. To: RON
6. Result: 50.00 € = 248.50 RON
```

### Example 3: Change Customer Display Currency to EUR
```
1. Go to Admin → Currency tab
2. Change "Customer Display Currency" to EUR
3. Click "Save Currency Settings"
4. Refresh customer portal
5. Customers now see prices in EUR
```

---

## Summary

✅ **What's Working:**
- Multi-currency support for 7 currencies
- Automatic EUR → RON conversion for customers
- Currency converter tool
- Configurable currency settings per cost type
- Real-time price conversion

✅ **Customer Experience:**
- All prices displayed in Romanian Lei (RON)
- Consistent formatting: `24.85 RON`
- No need to manually convert from EUR

✅ **Admin Control:**
- Manage costs in EUR (or any currency)
- Set display currency for customers
- Use converter for quick calculations
- View current exchange rates

---

## Files Modified/Created

### Created:
- [routes/currency.js](routes/currency.js) - Currency API endpoints
- [public/js/currency.js](public/js/currency.js) - Currency converter module
- [CURRENCY_GUIDE.md](CURRENCY_GUIDE.md) - This guide

### Modified:
- [database.js](database.js:122-138) - Added currency_settings table
- [server.js](server.js:12,31) - Added currency routes
- [views/admin-dashboard.html](views/admin-dashboard.html:27,159-234) - Added Currency tab
- [views/customer-portal.html](views/customer-portal.html:52) - Added currency.js script
- [public/js/admin.js](public/js/admin.js:45-47,1049-1095) - Currency tab functions
- [public/js/customer.js](public/js/customer.js:64-94,148-178) - RON price display

---

## Next Steps (Optional Enhancements)

1. **Automatic Rate Updates**: Integrate with exchange rate API for daily updates
2. **Historical Rates**: Track rate changes over time
3. **Multi-Currency Orders**: Allow customers to choose their preferred currency
4. **Currency Symbols**: Add more currency symbols and formatting rules
5. **Price History**: Track product prices in multiple currencies

---

**Server running at:** http://localhost:3000

**Login as:**
- Admin: admin@chocolate.com / admin123
- Customer: customer@example.com / customer123

**Test it out:** Login as a customer and see prices in Romanian Lei! 🇷🇴
