# Online Store Main Settings Controller Documentation

**File**: `/controllers/onlinestoremainsetting.php`  
**Purpose**: Manages core online store configuration including shipping, contact info, and branding  
**Last Updated**: December 20, 2024  
**Total Functions**: 2  
**Lines of Code**: ~76

---

## 📋 Overview

The Online Store Main Settings Controller manages the fundamental configuration settings for the online store. It handles the core business and operational settings that define how the online store operates, including:
- Store branding (logos for light/dark themes)
- Shipping configuration and pricing
- Contact information (addresses, phones, emails)
- Social media links
- Email/SMS service configuration (Twilio, SMTP)
- Store selection for inventory
- Multi-language address support

### Primary Functions
- [x] Display online store main settings form
- [x] Update store configuration with file uploads
- [x] Handle logo uploads (light and dark themes)
- [x] Configure shipping methods and pricing
- [x] Set contact information and social media
- [x] Configure email/SMS services
- [x] Select inventory stores for online display

### Related Controllers
- [onlinestoresetting.php](onlinestoresetting.md) - Advanced sync settings
- [onlinestoresync.php](onlinestoresync.md) - Data synchronization
- [storeController.php](storeController.md) - Store management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **onlinestoremainsetting** | Main online store configuration | logo, logo_dark, send_type, shipping settings, contact info, social media, email/SMS config |
| **store** | Available stores for selection | storeId, storeName, conditions |

---

## 🔑 Key Functions

### 1. **Default Action / Settings Display**
**Location**: Line 9  
**Purpose**: Display the online store main settings form

**Process Flow**:
1. Load current settings from `onlinestoremainsetting` table (ID=1)
2. Load available stores for selection
3. Assign data to template variables
4. Display edit form

**Template Variables**:
```php
$showData = R::load('onlinestoremainsetting', 1);
$stores = R::getAll('select storeId,storeName from store where conditions=0');
$smarty->assign('showData', $showData);
$smarty->assign('stores', $stores);
```

**Features**:
- Single record configuration (ID=1 always used)
- Store selection dropdown
- Form pre-populated with current values

---

### 2. **update() - Update Settings**
**Location**: Line 20  
**Purpose**: Update online store main settings with file upload support

**Process Flow**:
1. **Handle File Uploads**:
   - Process logo upload (light theme)
   - Process dark logo upload (dark theme)
   - Use `uploadupdate()` function for file handling

2. **Update Configuration Fields**:
   - Shipping configuration
   - Contact information  
   - Social media links
   - Email/SMS service settings
   - Store selection

3. **Save and Respond**:
   - Store updated record
   - Return JSON response for AJAX calls
   - Redirect for standard form submission

**Key Settings Updated**:

#### Shipping Configuration:
```php
$updateData->send_type = $_POST['send_type'];
$updateData->shippingfree_numberitems = $_POST['shippingfree_numberitems'];
$updateData->numberitems = $_POST['numberitems'];
$updateData->shippingfree_totleitems = $_POST['shippingfree_totleitems'];
$updateData->totleitems = $_POST['totleitems'];
$updateData->fixedshipping_value = $_POST['fixedshipping_value'];
$updateData->shipping_value = $_POST['shipping_value'];
```

#### Contact Information:
```php
$updateData->address_ar = $_POST['address_ar'];
$updateData->address_en = $_POST['address_en'];
$updateData->mobile = $_POST['mobile'];
$updateData->another_mobile = $_POST['another_mobile'];
$updateData->email = $_POST['email'];
$updateData->another_email = $_POST['another_email'];
```

#### Social Media:
```php
$updateData->facebook = $_POST['facebook'];
$updateData->twitter = $_POST['twitter'];
$updateData->instagram = $_POST['instagram'];
$updateData->telegram = $_POST['telegram'];
```

#### Email/SMS Services:
```php
// Twilio SMS Configuration
$updateData->account_sid = $_POST['account_sid'];
$updateData->auth_token = $_POST['auth_token'];
$updateData->twilio_number = $_POST['twilio_number'];

// SMTP Email Configuration  
$updateData->mail_host = $_POST['mail_host'];
$updateData->mail_port = $_POST['mail_port'];
$updateData->mail_username = $_POST['mail_username'];
$updateData->mail_password = $_POST['mail_password'];
$updateData->mail_encryption = $_POST['mail_encryption'];
$updateData->mail_fromaddress = $_POST['mail_fromaddress'];
```

#### File Upload Handling:
```php
$logo = uploadupdate('logo', 'logourl', False, 0, 0, 'onlinestoremainsetting');
$logo_dark = uploadupdate('logodark', 'logodarkurl', False, 0, 0, 'onlinestoremainsetting');
$updateData->logo = $logo;
$updateData->logo_dark = $logo_dark;
```

---

## 🔄 Workflows

### Workflow 1: Settings Configuration
```
┌─────────────────────────────────────────────────────────────┐
│                START: Configure Store Settings             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Current Settings                                   │
│     - Query onlinestoremainsetting table (ID=1)            │
│     - Load available stores list                            │
│     - Display settings form                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Configures Settings                                │
│     ┌─────────────────────────────────────────────────────┐ │
│     │ Branding:                                           │ │
│     │ - Upload store logo (light theme)                   │ │
│     │ - Upload store logo (dark theme)                    │ │
│     │                                                     │ │
│     │ Shipping:                                           │ │
│     │ - Shipping method type                              │ │
│     │ - Free shipping thresholds                          │ │
│     │ - Shipping costs and rules                          │ │
│     │                                                     │ │
│     │ Contact Information:                                │ │
│     │ - Business addresses (AR/EN)                        │ │
│     │ - Phone numbers                                     │ │
│     │ - Email addresses                                   │ │
│     │ - Social media links                                │ │
│     │                                                     │ │
│     │ Services:                                           │ │
│     │ - Twilio SMS configuration                          │ │
│     │ - SMTP email settings                               │ │
│     │ - Store selection for inventory                     │ │
│     └─────────────────────────────────────────────────────┘ │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Form Submission                                 │
│     ┌─────────────────────────────────────────────────────┐ │
│     │ File Uploads:                                       │ │
│     │ - Process logo uploads                              │ │
│     │ - Validate file types and sizes                     │ │
│     │ - Save to appropriate directories                   │ │
│     │                                                     │ │
│     │ Data Validation:                                    │ │
│     │ - Validate email addresses                          │ │
│     │ - Validate phone numbers                            │ │
│     │ - Validate shipping values                          │ │
│     │ - Validate store selection                          │ │
│     │                                                     │ │
│     │ Database Update:                                    │ │
│     │ - Update onlinestoremainsetting record              │ │
│     │ - Save all configuration fields                     │ │
│     └─────────────────────────────────────────────────────┘ │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Success/Error Response                                  │
│     ┌─────────────────┐         ┌─────────────────────────┐ │
│     │ AJAX Request?   │   YES   │ Return JSON Response     │ │
│     │                 │────────▶│ {status: 1, message:...} │ │
│     └─────────────────┘         └─────────────────────────┘ │
│             │                                               │
│             │ NO                                            │
│             ▼                                               │
│     ┌─────────────────────────────────────────────────────┐ │
│     │ Redirect to Settings Page                           │ │
│     │ - Show success message                              │ │
│     │ - Reload with updated values                        │ │
│     └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display settings form |
| `do=update` | `update()` | Save settings changes |

### Required Parameters for Update

**Shipping Configuration**:
- `send_type` - Shipping method type
- `shippingfree_numberitems` - Free shipping item threshold
- `numberitems` - Regular shipping item count
- `shippingfree_totleitems` - Free shipping total threshold
- `totleitems` - Regular shipping total
- `fixedshipping_value` - Fixed shipping cost
- `shipping_value` - Variable shipping cost

**Contact Information**:
- `address_ar` - Arabic address
- `address_en` - English address
- `mobile` - Primary phone number
- `another_mobile` - Secondary phone number
- `email` - Primary email address
- `another_email` - Secondary email address

**Social Media**:
- `facebook` - Facebook page URL
- `twitter` - Twitter account URL
- `instagram` - Instagram account URL
- `telegram` - Telegram contact

**Service Configuration**:
- `account_sid` - Twilio account SID
- `auth_token` - Twilio auth token
- `twilio_number` - Twilio phone number
- `mail_host` - SMTP server host
- `mail_port` - SMTP server port
- `mail_username` - SMTP username
- `mail_password` - SMTP password
- `mail_encryption` - SMTP encryption type
- `mail_fromaddress` - Email from address
- `store` - Selected store for inventory

**File Uploads**:
- `logo` - Store logo file (light theme)
- `logodark` - Store logo file (dark theme)

---

## 🧮 Configuration Logic

### Shipping Rules Configuration
The system supports various shipping methods and thresholds:

1. **Free Shipping by Item Count**:
   - `shippingfree_numberitems`: Minimum items for free shipping
   - `numberitems`: Regular shipping item threshold

2. **Free Shipping by Total Amount**:
   - `shippingfree_totleitems`: Minimum total for free shipping
   - `totleitems`: Regular shipping total threshold

3. **Shipping Cost Structure**:
   - `fixedshipping_value`: Fixed shipping cost
   - `shipping_value`: Variable shipping calculation

### File Upload Handling
```php
// Logo upload with validation
$logo = uploadupdate('logo', 'logourl', False, 0, 0, 'onlinestoremainsetting');
$logo_dark = uploadupdate('logodark', 'logodarkurl', False, 0, 0, 'onlinestoremainsetting');

// Parameters:
// - Field name from form
// - URL field name (for fallback)
// - Resize flag (False = no resize)
// - Width (0 = original)
// - Height (0 = original)  
// - Directory prefix
```

---

## 🔒 Security & Permissions

### File Upload Security
- File type validation through `uploadupdate()` function
- Directory restrictions to prevent path traversal
- File size limitations

### Input Validation
- Email address format validation
- Phone number format checking
- URL validation for social media links
- Numeric validation for shipping values

### Access Control
- Requires valid session for access
- Admin-level permissions typically required
- CSRF protection through session validation

---

## 📊 Performance Considerations

### Database Optimization
1. **Single Record Pattern**:
   - Always uses ID=1 for settings
   - No indexing needed beyond primary key
   - Fast single-record lookups

2. **Store Selection**:
   - Efficient store query with conditions filter
   - Small result set for dropdown

### File Upload Performance
- Image optimization during upload
- Proper file storage organization
- Cache considerations for logo display

---

## 🐛 Common Issues & Troubleshooting

### 1. **Logo Upload Failures**
**Issue**: Logos not uploading or displaying  
**Cause**: File permissions, invalid file types, or size limits

**Debug Steps**:
```php
// Check upload directory permissions
// Verify file types allowed in uploadupdate() function
// Check PHP upload_max_filesize and post_max_size settings
```

### 2. **Settings Not Saving**
**Issue**: Form submission successful but settings unchanged  
**Cause**: Database connection issues or field name mismatches

**Debug**:
```sql
-- Check if record exists
SELECT * FROM onlinestoremainsetting WHERE id = 1;

-- Verify field names match POST data
DESCRIBE onlinestoremainsetting;
```

### 3. **SMTP Configuration Issues**
**Issue**: Email configuration not working  
**Cause**: Incorrect SMTP settings or firewall blocks

**Test Configuration**:
```php
// Test SMTP connection manually
// Verify host, port, encryption settings
// Check authentication credentials
```

### 4. **Store Selection Not Working**
**Issue**: Store dropdown empty or not saving  
**Cause**: Inactive stores or conditions filter

**Debug Query**:
```sql
SELECT storeId, storeName, conditions FROM store WHERE conditions = 0;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Configuration
```
1. Load settings form
2. Verify current values displayed
3. Update basic contact information
4. Save and verify changes
5. Check form reload shows new values
```

### Test Case 2: Logo Upload
```
1. Prepare test image files (light/dark themes)
2. Upload logos through form
3. Verify files saved to correct directories
4. Check database contains file references
5. Verify logos display on frontend
```

### Test Case 3: Shipping Configuration
```
1. Set various shipping rules
2. Test free shipping thresholds
3. Configure multiple shipping options
4. Verify frontend shipping calculations
5. Test edge cases (zero values, very high thresholds)
```

### Test Case 4: Service Integration
```
1. Configure Twilio SMS settings
2. Test SMS functionality
3. Configure SMTP email settings  
4. Test email sending
5. Verify error handling for invalid credentials
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [onlinestoresetting.md](onlinestoresetting.md) - Advanced sync settings
- [onlinestoresync.md](onlinestoresync.md) - Data synchronization
- [storeController.md](storeController.md) - Store management

---

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