# Production Setup Guide

This guide will help you set up MarsZone for the first time in a production environment.

## Prerequisites

- PHP 8.1 or higher
- MySQL 5.7+ or MariaDB 10.3+
- Composer installed
- Web server (Apache/Nginx)

## Installation Steps

### 1. Clone or Upload Project

```bash
# Clone from repository
git clone https://github.com/MarsExpressIT/marszone.git
cd marszone

# Or upload your project files to server
```

### 2. Install Dependencies

```bash
composer install --no-dev --optimize-autoloader
```

### 3. Configure Environment

Copy the environment file:

```bash
cp env .env
```

Edit `.env` file and configure:

```env
# Environment
CI_ENVIRONMENT = production

# Base URL
app.baseURL = 'https://yourdomain.com/'

# Database Configuration
database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_db_username
database.default.password = your_db_password
database.default.DBDriver = MySQLi
database.default.port = 3306

# Encryption Key (IMPORTANT: Generate new key!)
encryption.key = your_32_character_encryption_key

# Session Configuration
app.sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler'
app.sessionSavePath = 'ci_sessions'

# Email Configuration (for forgot password)
email.fromEmail = noreply@yourdomain.com
email.fromName = 'MarsZone System'
email.SMTPHost = your_smtp_host
email.SMTPUser = your_smtp_username
email.SMTPPass = your_smtp_password
email.SMTPPort = 587
email.SMTPCrypto = tls
```

### 4. Generate Encryption Key

```bash
php spark key:generate
```

This will automatically update your `.env` file with a secure encryption key.

### 5. Set File Permissions

```bash
# Make writable directory writable
chmod -R 775 writable/
chown -R www-data:www-data writable/

# Make uploads directory writable
chmod -R 775 uploads/
chown -R www-data:www-data uploads/
```

### 6. Run Database Migrations

```bash
php spark migrate
```

This will create all necessary database tables:
- ✅ users
- ✅ roles
- ✅ permissions
- ✅ model_has_roles
- ✅ model_has_permissions
- ✅ role_has_permissions
- ✅ user_fcm_tokens
- ✅ password_resets
- ✅ notification_templates
- ✅ notifications
- ✅ notification_reads
- ✅ activity_logs
- ✅ ci_sessions

### 7. Seed Production Data

**IMPORTANT**: This is a one-time operation for initial setup.

```bash
php spark db:seed ProductionSeeder
```

The seeder will:
1. ✅ Create all web permissions (18 permissions)
   - users.can-list, users.can-create, users.can-update, users.can-delete, users.can-import, users.can-block-unblock
   - users.can-assign-web-permissions, users.can-assign-app-permissions, users.can-assign-api-permissions
   - roles.can-list, roles.can-create, roles.can-update, roles.can-delete, roles.can-assign-permissions
   - notifications.can-list, notifications.can-create, notifications.can-update, notifications.can-delete

2. ✅ Create all app permissions (4 permissions)
   - menu.can-view-home, menu.can-view-more
   - notifications.can-receive, notifications.can-view-list

3. ✅ Create all API permissions (1 permission)
   - users.can-register-user

4. ✅ Create default Admin role with all permissions assigned

5. ✅ Create three default users:

| Role          | Email                   | Password | Employee Number |
|---------------|-------------------------|----------|-----------------|
| Administrator | admin@marszone.com      | password | EMP001          |
| Manager       | manager@marszone.com    | password | EMP002          |
| User          | user@marszone.com       | password | EMP003          |

### 8. Login and Change Passwords

⚠️ **CRITICAL SECURITY STEP**: After running the seeder, immediately:

1. Login to the system at `https://yourdomain.com/login`
2. Use the default credentials above
3. **Change all default passwords immediately**
4. Update user information (names, emails, employee numbers)

### 9. Configure Web Server

#### Apache (.htaccess)

Create/verify `.htaccess` in public folder:

```apache
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
```

#### Nginx

Add to your nginx configuration:

```nginx
server {
    listen 80;
    server_name yourdomain.com;
    root /path/to/marszone/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}
```

### 10. Enable HTTPS (Recommended)

```bash
# Using Let's Encrypt (Certbot)
sudo certbot --nginx -d yourdomain.com
```

### 11. Setup Cron Jobs (Optional)

If you need scheduled tasks, add to crontab:

```bash
# Edit crontab
crontab -e

# Add this line (runs every minute)
* * * * * cd /path/to/marszone && php spark schedule:run >> /dev/null 2>&1
```

## Post-Installation Checklist

- [ ] Database migrations completed
- [ ] Production seeder executed
- [ ] All default passwords changed
- [ ] Email configuration tested (forgot password)
- [ ] File permissions set correctly
- [ ] HTTPS enabled
- [ ] Admin user email updated to real email
- [ ] Backup strategy implemented
- [ ] Monitoring/logging configured

## Security Best Practices

1. **Never use default passwords in production**
2. **Keep encryption key secret and secure**
3. **Enable HTTPS/SSL**
4. **Regular database backups**
5. **Keep CodeIgniter and dependencies updated**
6. **Monitor application logs**
7. **Implement rate limiting for login attempts**
8. **Use strong passwords**
9. **Regular security audits**

## Backup Strategy

### Database Backup

```bash
# Daily backup script
mysqldump -u username -p database_name > backup_$(date +%Y%m%d).sql

# Compress backup
gzip backup_$(date +%Y%m%d).sql
```

### File Backup

```bash
# Backup uploads and writable folders
tar -czf backup_files_$(date +%Y%m%d).tar.gz uploads/ writable/
```

## Troubleshooting

### Issue: Permission Denied

```bash
chmod -R 775 writable/
chown -R www-data:www-data writable/
```

### Issue: Database Connection Error

Check `.env` database configuration and ensure:
- Database exists
- User has proper permissions
- Host/port are correct

### Issue: 404 on All Pages

Check web server configuration:
- Apache: Ensure mod_rewrite is enabled
- Nginx: Verify try_files directive

### Issue: Session Not Working

Ensure:
- `ci_sessions` table exists (run migrations)
- writable/session directory is writable
- Session configuration in `.env` is correct

## Support

For issues or questions:
- Check documentation: [CodeIgniter 4 Docs](https://codeigniter.com/user_guide/)
- Review logs in `writable/logs/`
- Contact support team

## License

This project is proprietary software developed by MarsExpress IT.

---

**Last Updated**: October 31, 2025
