# Multi-Tenant POS System - Deployment Guide

## Overview
This guide explains how to deploy your POS system with multi-tenant support where multiple clients share the same source code but use separate databases.

---

## Architecture

### Single Source Code, Multiple Databases
```
Source Code (One Location):
/var/www/html/pos/

Subdomains (Multiple Clients):
├── client1.bitsoft-bd.com → webPos_client1 database
├── client2.bitsoft-bd.com → webPos_client2 database
└── client3.bitsoft-bd.com → webPos_client3 database
```

---

## How It Works

### Automatic Tenant Detection
The system automatically detects which client is accessing based on the subdomain:

1. User visits: `client1.bitsoft-bd.com`
2. System detects subdomain: `client1`
3. Loads database: `webPos_client1`
4. All operations use Client 1's isolated database

**No code changes needed** - everything happens automatically!

---

## Step-by-Step Deployment

### Step 1: Prepare Databases

Create separate databases for each client:

```sql
-- Connect to MySQL
mysql -u root -p

-- Create databases
CREATE DATABASE webPos_client1 CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE DATABASE webPos_client2 CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE DATABASE webPos_client3 CHARACTER SET utf8 COLLATE utf8_general_ci;

-- (Optional but RECOMMENDED) Create separate users for security
CREATE USER 'client1_user'@'localhost' IDENTIFIED BY 'strong_password_1';
CREATE USER 'client2_user'@'localhost' IDENTIFIED BY 'strong_password_2';
CREATE USER 'client3_user'@'localhost' IDENTIFIED BY 'strong_password_3';

-- Grant permissions
GRANT ALL PRIVILEGES ON webPos_client1.* TO 'client1_user'@'localhost';
GRANT ALL PRIVILEGES ON webPos_client2.* TO 'client2_user'@'localhost';
GRANT ALL PRIVILEGES ON webPos_client3.* TO 'client3_user'@'localhost';

FLUSH PRIVILEGES;
```

### Step 2: Import Database Schema

Import your POS database structure into each client database:

```bash
# For Client 1
mysql -u root -p webPos_client1 < pos_database_schema.sql

# For Client 2
mysql -u root -p webPos_client2 < pos_database_schema.sql

# For Client 3
mysql -u root -p webPos_client3 < pos_database_schema.sql
```

### Step 3: Update Tenant Database Configuration

Edit `application/config/tenant_databases.php` and update credentials:

```php
'client1' => array(
    'hostname' => 'localhost',
    'username' => 'client1_user',  // Update this
    'password' => 'strong_password_1',  // Update this
    'database' => 'webPos_client1',
    // ... rest of config
),

'client2' => array(
    'hostname' => 'localhost',
    'username' => 'client2_user',  // Update this
    'password' => 'strong_password_2',  // Update this
    'database' => 'webPos_client2',
    // ... rest of config
),

'client3' => array(
    'hostname' => 'localhost',
    'username' => 'client3_user',  // Update this
    'password' => 'strong_password_3',  // Update this
    'database' => 'webPos_client3',
    // ... rest of config
),
```

### Step 4: Configure Apache Virtual Hosts

Create Apache configuration for each subdomain pointing to the same source code:

**File:** `/etc/apache2/sites-available/pos-multitenantconf`

```apache
# Client 1 Subdomain
<VirtualHost *:80>
    ServerName client1.bitsoft-bd.com
    DocumentRoot /var/www/html/pos

    <Directory /var/www/html/pos>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/client1_error.log
    CustomLog ${APACHE_LOG_DIR}/client1_access.log combined
</VirtualHost>

# Client 2 Subdomain
<VirtualHost *:80>
    ServerName client2.bitsoft-bd.com
    DocumentRoot /var/www/html/pos

    <Directory /var/www/html/pos>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/client2_error.log
    CustomLog ${APACHE_LOG_DIR}/client2_access.log combined
</VirtualHost>

# Client 3 Subdomain
<VirtualHost *:80>
    ServerName client3.bitsoft-bd.com
    DocumentRoot /var/www/html/pos

    <Directory /var/www/html/pos>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/client3_error.log
    CustomLog ${APACHE_LOG_DIR}/client3_access.log combined
</VirtualHost>
```

Enable the configuration:

```bash
sudo a2ensite pos-multitenant
sudo systemctl reload apache2
```

### Step 5: Configure DNS

Add subdomain DNS records in your domain panel:

```
Type    Name       Value                TTL
A       client1    your_server_ip       300
A       client2    your_server_ip       300
A       client3    your_server_ip       300
```

### Step 6: Install SSL Certificates (IMPORTANT!)

Use Let's Encrypt for free SSL:

```bash
sudo certbot --apache -d client1.bitsoft-bd.com
sudo certbot --apache -d client2.bitsoft-bd.com
sudo certbot --apache -d client3.bitsoft-bd.com
```

---

## Testing

### Local Testing (Before Deployment)

Add to your local hosts file for testing:

**Windows:** `C:\Windows\System32\drivers\etc\hosts`
**Linux/Mac:** `/etc/hosts`

```
127.0.0.1  client1.bitsoft-bd.com
127.0.0.1  client2.bitsoft-bd.com
127.0.0.1  client3.bitsoft-bd.com
```

Create test databases locally:
```sql
CREATE DATABASE webPos_client1;
CREATE DATABASE webPos_client2;
CREATE DATABASE webPos_client3;
```

Visit in browser:
- http://client1.bitsoft-bd.com
- http://client2.bitsoft-bd.com
- http://client3.bitsoft-bd.com

Each should connect to its own database!

---

## Adding New Clients

To add Client 4, Client 5, etc.:

### 1. Create Database
```sql
CREATE DATABASE webPos_client4;
CREATE USER 'client4_user'@'localhost' IDENTIFIED BY 'password4';
GRANT ALL ON webPos_client4.* TO 'client4_user'@'localhost';
FLUSH PRIVILEGES;
```

### 2. Add to tenant_databases.php
```php
'client4' => array(
    'hostname' => 'localhost',
    'username' => 'client4_user',
    'password' => 'password4',
    'database' => 'webPos_client4',
    // ... same config as others
),
```

### 3. Add Apache VirtualHost
Copy existing VirtualHost block and change to `client4.bitsoft-bd.com`

### 4. Add DNS Record
Add A record for `client4` pointing to server IP

### 5. Get SSL Certificate
```bash
sudo certbot --apache -d client4.bitsoft-bd.com
```

That's it! No code changes needed!

---

## Security Best Practices

### 1. Move Configuration Outside Web Root

```bash
# Create secure config directory
sudo mkdir -p /var/www/pos_configs
sudo chown www-data:www-data /var/www/pos_configs
sudo chmod 750 /var/www/pos_configs

# Move tenant config
sudo mv /var/www/html/pos/application/config/tenant_databases.php /var/www/pos_configs/

# Update database.php to load from new location
require_once('/var/www/pos_configs/tenant_databases.php');
```

### 2. Use Environment Variables

Create `.env` file per subdomain (requires additional setup):

```bash
DB_CLIENT1_HOST=localhost
DB_CLIENT1_USER=client1_user
DB_CLIENT1_PASS=secure_password
DB_CLIENT1_NAME=webPos_client1
```

### 3. Separate Database Users

Each client should have its own MySQL user with access ONLY to their database.

### 4. Enable Firewall Rules

```bash
sudo ufw allow 'Apache Full'
sudo ufw enable
```

### 5. Regular Backups

Set up automatic backups for each database:

```bash
#!/bin/bash
# Daily backup script
mysqldump -u backup_user -p webPos_client1 > /backups/client1_$(date +%Y%m%d).sql
mysqldump -u backup_user -p webPos_client2 > /backups/client2_$(date +%Y%m%d).sql
mysqldump -u backup_user -p webPos_client3 > /backups/client3_$(date +%Y%m%d).sql
```

Add to cron: `0 2 * * * /path/to/backup_script.sh`

---

## Troubleshooting

### Issue: "Access Denied" Error

**Solution:** Check database credentials in `tenant_databases.php` are correct.

```bash
# Test database connection
mysql -u client1_user -p webPos_client1
```

### Issue: Wrong Database Being Used

**Solution:** Enable debug logging in `database.php`:

```php
if (ENVIRONMENT === 'development') {
    error_log("POS System - Tenant: {$current_tenant}, Database: {$db['default']['database']}");
}
```

Check Apache error log:
```bash
tail -f /var/log/apache2/client1_error.log
```

### Issue: Subdomain Not Resolving

**Solution:**
1. Check DNS propagation: https://dnschecker.org
2. Verify Apache VirtualHost is enabled
3. Restart Apache: `sudo systemctl restart apache2`

### Issue: SSL Certificate Errors

**Solution:**
```bash
# Renew certificates
sudo certbot renew

# Check certificate status
sudo certbot certificates
```

---

## Monitoring

### Check Which Database Each Request Uses

Add to `database.php` (development only):

```php
if (ENVIRONMENT === 'development') {
    $log_file = FCPATH . 'tenant_access.log';
    $log_entry = date('Y-m-d H:i:s') . " | Host: {$_SERVER['HTTP_HOST']} | Tenant: {$current_tenant} | DB: {$db['default']['database']}\n";
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}
```

### Monitor Database Connections

```bash
# Show current MySQL connections
mysqladmin -u root -p processlist

# Monitor in real-time
watch -n 2 'mysqladmin -u root -p processlist'
```

---

## Performance Optimization

### Enable Query Caching Per Client

In `tenant_databases.php`, enable caching:

```php
'client1' => array(
    // ... other config
    'cache_on' => TRUE,
    'cachedir' => APPPATH . 'cache/client1/',
),
```

Create cache directories:
```bash
mkdir -p application/cache/client1
mkdir -p application/cache/client2
mkdir -p application/cache/client3
chmod -R 777 application/cache/
```

### Database Connection Pooling

For high traffic, consider enabling persistent connections:

```php
'pconnect' => TRUE,  // In tenant_databases.php
```

---

## Maintenance

### Update All Client Databases

When database schema changes:

```bash
# Run migration on all databases
for db in webPos_client1 webPos_client2 webPos_client3; do
    mysql -u root -p $db < database_migration.sql
done
```

### Update Source Code

Since all clients share the same code:

```bash
cd /var/www/html/pos
git pull origin main
# All clients automatically use updated code!
```

---

## Summary

✅ **One source code** - Easy to maintain and update
✅ **Separate databases** - Complete data isolation per client
✅ **Automatic detection** - No manual configuration per request
✅ **Scalable** - Easy to add new clients
✅ **Secure** - Separate credentials per tenant
✅ **Production-ready** - Tested and reliable

---

## Support

For issues or questions:
- Email: support@bitsoft-bd.com
- Check logs: `/var/log/apache2/clientX_error.log`
- Enable debug mode in CodeIgniter for detailed errors

---

**Last Updated:** <?= date('Y-m-d'); ?>
**Version:** 1.0
