# Program Settings Controller Documentation

**File**: `/controllers/programsettingsController.php`  
**Purpose**: Manages system-wide configuration, company settings, and global behavior  
**Last Updated**: December 19, 2024  
**Total Functions**: 5  
**Lines of Code**: ~903

---

## 📋 Overview

The Program Settings Controller is the central component for managing system-wide configuration and global settings in the ERP system. It handles:
- Company information and branding
- System behavior and feature toggles
- Multi-currency and localization settings
- Restaurant and POS configurations
- E-invoice and tax settings
- Product and inventory defaults
- UI customization and display options
- Image and document management
- Database structure modifications
- Integration settings for external systems

### Primary Functions
- [x] Update comprehensive system settings
- [x] Company profile management
- [x] Feature toggle configuration
- [x] Currency and localization setup
- [x] Tax and e-invoice configuration
- [x] Restaurant/cafe specific settings
- [x] Product behavior defaults
- [x] UI customization options
- [x] File upload management
- [x] Database structure adjustments

### Related Controllers
- [userController.php](userController.md) - User management
- [usergroupController.php](usergroupController.md) - User group management
- [billsettingsController.php](billsettingsController.md) - Bill templates
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations
- [productController.php](productController.md) - Product management
- [storeController.php](storeController.md) - Store management
- [clientController.php](clientController.md) - Customer management
- [supplierController.php](supplierController.md) - Supplier management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **programsettings** | System configuration | programsettingsid, companyname, address, phone, email, logo, timezone |
| **ebillsetting** | E-invoice configuration | id, eunitInTax, eTaxNum, eTaxNumBranch, eGovernorate, eCity |
| **transfersell** | Transfer settings | Special business transfer settings |

### Configuration Categories in programsettings Table
| Category | Purpose | Key Fields |
|----------|---------|------------|
| **Company Info** | Business identity | companyname, address, phone, email, website, logo |
| **Financial** | Money settings | currency, roundnumbers, vatValue, valueadded |
| **Product Settings** | Item behavior | parcode, limitamount, measuringunit, updateproductprice |
| **UI Settings** | Display options | searchlimit, colortype, noOfDecimalPlaces |
| **Restaurant** | POS features | isRestaurent, isCafe, restaurantStoreId, takeAwayClient |
| **Printing** | Output options | printingpapersize, saveprinting, deptprinting |
| **E-Invoice** | Tax compliance | ebill, saudielectronicinvoice, vatvalueqr |
| **Integration** | External systems | qrerp, webApiId, tamweenBakery |

### Reference Tables
| Table Name | Purpose | Relationship |
|------------|---------|-------------|
| **store** | Warehouses | programsettings.restaurantStoreId |
| **usergroup** | User roles | Used for pharmacy group settings |
| **productcat** | Product categories | Used for medical categories |
| **expensestype** | Expense types | Used for dollar expense types |

---

## 🔧 Key Functions

### 1. **Default Display** - Load Configuration Form
**Location**: Line 117  
**Purpose**: Load and display the comprehensive system settings form

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Current    │───▶│ Process Arrays   │───▶│ Load Reference  │
│ Settings        │    │ (Explode CSV)    │    │ Data            │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
┌─────────▼───────┐    ┌──────────▼──────┐    ┌──────────▼──────┐
│ Assign Smarty   │    │ Load Stores     │    │ Load User Groups│
│ Variables       │    │ Categories      │    │ & Categories    │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

### 2. **update()** - Update System Configuration
**Location**: Line 171  
**Purpose**: Comprehensive update of all system settings with validation and processing

**Function Signature**:
```php
function update()
```

**Key Parameters** (via $_POST - over 200 settings):

**Company Information**:
- `companyname` - Business name
- `address` - Business address
- `phone`, `faxnumber`, `email`, `website` - Contact info
- `taxcard`, `commercialregistration`, `licenseNo` - Legal info

**System Behavior**:
- `roundnumbers` - Number rounding
- `searchlimit` - Search result limits
- `timezone` - System timezone
- `noOfDecimalPlaces` - Decimal precision
- `enablequantityfractions` - Fractional quantities

**Product Settings**:
- `parcode` - Barcode settings
- `parcodeDigits` - Barcode length
- `limitamount` - Stock alert levels
- `updateproductprice` - Price update behavior

**Financial Configuration**:
- `currancy` - System currency
- `vatValue` - VAT percentage
- `valueadded` - VAT application
- `clientDefaultDebtLimit` - Credit limits

**Restaurant/POS Settings**:
- `isRestaurent`, `isCafe` - Operation mode
- `restaurantStoreId` - Default store
- `takeAwayClient` - Takeaway customer
- `hall`, `delivery`, `takeAway` - Service types

**E-Invoice Configuration**:
- `ebill` - E-invoice enabled
- `saudielectronicinvoice` - Saudi ZATCA
- `eTaxNum` - Tax registration number

### 3. **affectTableStructureWithDecimalPlaces()** - Database Schema Updates
**Location**: Line 847  
**Purpose**: Modify database table structure based on decimal place settings

**Parameters**:
- `noOfDecimalPlacesBillTotal` - Bill total precision
- `noOfDecimalPlaces` - General decimal precision

**Process**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Calculate       │───▶│ Build ALTER      │───▶│ Execute SQL     │
│ New Precision   │    │ TABLE Queries    │    │ for Each Table  │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Tables Modified**:
- `sellbill` - Sales totals, payments
- `sellbilldetail` - Line item amounts

### 4. **CURL_IT()** - External API Communication
**Location**: Line 863  
**Purpose**: Send company data to external QR ERP system

### 5. **addPreDigitsToNum()** - Barcode Formatting
**Location**: Line 888  
**Purpose**: Format numbers with leading zeros for barcode generation

---

## 🔄 Business Logic Flow

### Settings Update Workflow
```
┌─────────────────┐
│ Form Submission │
│ (200+ Fields)   │
└─────────┬───────┘
          │
┌─────────▼───────┐    ┌──────────────────┐
│ Validate Input  │───▶│ Process Images   │
│ & Type Cast     │    │ (Logo, Headers)  │
└─────────────────┘    └──────────────────┘
          │                       │
┌─────────▼───────┐    ┌──────────▼──────┐
│ Array Processing│───▶│ Load Existing   │
│ (Comma-separated│    │ Settings        │
│  values)        │    └─────────────────┘
└─────────────────┘               │
          │                       │
┌─────────▼───────┐    ┌──────────▼──────┐
│ Database Update │───▶│ Structure       │
│ (Programsettings│    │ Modifications   │
│  & Ebillsetting)│    └─────────────────┘
└─────────────────┘               │
          │                       │
┌─────────▼───────┐    ┌──────────▼──────┐
│ Cache           │───▶│ External API    │
│ Invalidation    │    │ Updates         │
└─────────────────┘    └─────────────────┘
```

### Restaurant Service Configuration
```
                    ┌─────────────────┐
                    │ Restaurant      │
                    │ Settings        │
                    └─────────┬───────┘
                              │
      ┌───────────────────────┼───────────────────────┐
      │                       │                       │
┌─────▼─────┐      ┌─────────▼────────┐      ┌─────▼─────┐
│ Hall      │      │ Takeaway         │      │ Delivery  │
│ Service   │      │ Service          │      │ Service   │
└───────────┘      └──────────────────┘      └───────────┘
      │                       │                       │
┌─────▼─────┐      ┌─────────▼────────┐      ┌─────▼─────┐
│ Table     │      │ Counter          │      │ Driver    │
│ Management│      │ Operations       │      │ Management│
└───────────┘      └──────────────────┘      └───────────┘
```

---

## ⚠️ Common Issues

### Image Upload Processing
**Issue**: Multiple image uploads with different resize requirements
```php
// ✅ IMPLEMENTED: Lines 428-444 - Different upload handlers
updateImages() // For logos (250x250)
updateImagesWithoutresiz() // For headers (original size)
```

### Database Schema Changes
**Issue**: Decimal precision changes require table structure modifications
```php
// ✅ SOLUTION: Lines 844-861 - Dynamic ALTER TABLE queries
affectTableStructureWithDecimalPlaces($noOfDecimalPlacesBillTotal, $noOfDecimalPlaces);
```

### Barcode Generation
**Issue**: Barcode digit changes require regenerating all product codes
```php
// ✅ IMPLEMENTED: Lines 788-810 - Barcode regeneration
if ($oldParcodeDigits != $parcodeDigits) {
    $availableParcodeEX->truncate();
    $availableParcodeEX->callGenerateParcodesSP($parcodeDigits);
}
```

### Performance Considerations
- **Cache Invalidation**: Header cache cleared on sync structure changes
- **External API**: QR ERP updates only when connected to internet
- **Database Changes**: Schema modifications can be time-consuming

---

## 🔗 Dependencies

### Required DAOs
- `ProgramsettingsMySqlDAO` - Main settings operations
- `ProgramsettingsMySqlExtDAO` - Extended settings queries
- `EbillsettingMySqlDAO` - E-invoice settings
- `StoreMySqlDAO` - Store configuration
- `UsergroupMySqlDAO` - User group settings
- `ClientMySqlExtDAO` - Client debt limit updates
- `AvailableparcodeMySqlExtDAO` - Barcode management

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Configuration
- `../library/uploadImages.php` - Image processing
- `../public/include_dao.php` - DAO includes

### External Dependencies
- Image processing libraries for logos/headers
- Internet connectivity for QR ERP integration
- Database ALTER privileges for structure changes
- File system access for image storage

---

## 🚀 Performance Notes

- Single comprehensive update function handles 200+ settings
- Image uploads processed asynchronously
- Database structure changes executed in batch
- External API calls wrapped in connectivity checks
- Cache management for performance optimization
- Array processing for multi-select configurations

The Program Settings Controller serves as the nerve center of the ERP system, controlling global behavior and ensuring consistent operation across all modules.