# Backup & Deployment Strategy
## With Nextcloud Integration

---

## TL;DR - What You Need to Do

### Your Current Workflow (Keep It!)
```bash
# Just keep doing this - nothing changes
git add .
git commit -m "your changes"
git push
```

**✅ GitHub handles**: All your code, database migrations, configurations  
**✅ Nextcloud handles**: All uploaded documents (PDFs, images, contracts, etc.)  
**❌ Don't commit**: Never commit uploaded files to Git

---

## What Changed with Nextcloud

### Before Nextcloud
- Documents stored in: `/public/uploads/`
- You had to manually backup that folder
- Files would be lost if not in Git or backed up separately

### After Nextcloud
- Documents stored in: **Nextcloud cloud storage**
- Automatic versioning and backup (via Nextcloud AIO's BorgBackup)
- Never touch Git - files live in the cloud

---

## Two Separate Systems

### 1. **Code & Database** → Git/GitHub
**What goes here:**
- ✅ PHP code (controllers, models, views)
- ✅ Database migrations (`.sql` files)
- ✅ Configuration files
- ✅ JavaScript, CSS, assets
- ✅ Documentation

**Your workflow (unchanged):**
```bash
git add .
git commit -m "Added feature X"
git push
```

**Backup:** Automatic via GitHub (cloud)

---

### 2. **Uploaded Documents** → Nextcloud
**What goes here:**
- ✅ Customer contracts
- ✅ Employee documents
- ✅ Invoice attachments
- ✅ Quote PDFs
- ✅ Project files
- ✅ All user-uploaded content

**Your workflow:** Nothing! Users upload via the ERP, automatically stored in Nextcloud

**Backup:** Automatic via Nextcloud AIO's BorgBackup

---

## .gitignore Setup

Make sure your `.gitignore` excludes uploads:

```
# Uploads (handled by Nextcloud)
/public/uploads/
/uploads/

# Environment config
.env
config/database.php

# System files
.DS_Store
Thumbs.db
```

---

## Deployment Strategy

### Development → Production

#### Step 1: Deploy Code (Git)
```bash
# On production server
cd /var/www/m1_erp_web
git pull origin main

# Run any new migrations
mysql -u user -p database_name < database/migrations/XXX_new_migration.sql

# Set permissions
chmod -R 755 .
chmod -R 777 uploads/  # legacy, might not be needed
```

#### Step 2: Nextcloud Setup (One-Time)
On production server, install Nextcloud AIO:

```bash
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

# Install Nextcloud AIO
sudo docker run -d \
  --name nextcloud-aio-mastercontainer \
  --restart always \
  -p 8090:8080 \
  -e APACHE_PORT=11000 \
  -e SKIP_DOMAIN_VALIDATION=true \
  -v nextcloud_aio_mastercontainer:/mnt/docker-aio-config \
  nextcloud/all-in-one:latest

# Access at https://server-ip:8090
# Set admin password, complete setup
```

#### Step 3: Configure ERP to Connect
In production ERP:
1. Go to `/nextcloud/settings`
2. Enter Nextcloud URL: `http://production-server:11000`
3. Enter admin credentials
4. Test connection
5. Enable integration

**That's it!** Nextcloud handles all file storage from that point forward.

---

## Backup Strategy

### What's Backed Up Where

| Data Type | Backup Location | Frequency | Retention |
|-----------|----------------|-----------|-----------|
| **Code** | GitHub | On push | Forever |
| **Database Schema** | GitHub (migrations) | On push | Forever |
| **Database Data** | Manual MySQL dump | Daily* | 30 days* |
| **Documents** | Nextcloud BorgBackup | Daily | 30 days |

*Recommended - set up automated script

---

## Automated Database Backup (Recommended)

Create `/home/yourusername/backup_db.sh`:

```bash
#!/bin/bash
# Daily database backup script

BACKUP_DIR="/home/yourusername/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="brickwal_m1_ds"
DB_USER="rpmbbu"

mkdir -p $BACKUP_DIR

# Backup with password from file (create ~/.my.cnf)
mysqldump -u $DB_USER $DB_NAME | gzip > "$BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz"

# Keep only last 30 days
find $BACKUP_DIR -name "*.sql.gz" -mtime +30 -delete

echo "Backup completed: ${DB_NAME}_${DATE}.sql.gz"
```

Setup password file `~/.my.cnf`:
```
[client]
password=your_mysql_password
```

```bash
chmod 600 ~/.my.cnf
chmod +x ~/backup_db.sh
```

Add to crontab:
```bash
crontab -e
# Add line:
0 2 * * * /home/yourusername/backup_db.sh
```

---

## Nextcloud Backup (Built-In)

Nextcloud AIO includes **BorgBackup** automatically.

### Enable Automatic Backups
1. Open Nextcloud AIO interface: `https://localhost:8090`
2. Click **"Backup and Restore"**
3. Configure backup location (external drive/NFS/S3)
4. Set schedule (daily recommended)
5. Enable automatic backups

### Backup Includes
- All uploaded documents
- Nextcloud database
- User data and settings
- File versions and history

### Manual Backup
```bash
# Backup now
docker exec nextcloud-aio-mastercontainer \
  php /var/www/docker-aio/php/src/Cron/backup.php

# List backups
docker exec nextcloud-aio-mastercontainer \
  borg list /mnt/borgbackup

# Restore from backup
# Use AIO web interface: https://localhost:8090 → Backup & Restore → Restore
```

---

## Disaster Recovery

### Scenario 1: Code Loss
**Recovery:**
```bash
git clone https://github.com/yourusername/m1_erp.git
cd m1_erp
# Setup database, restore from backup
# Connect to existing Nextcloud instance
```
**Time:** 15-30 minutes  
**Data Loss:** None (if DB backed up recently)

### Scenario 2: Database Corruption
**Recovery:**
```bash
# Restore from latest backup
gunzip < backup_20241118_020000.sql.gz | mysql -u rpmbbu -p brickwal_m1_ds
```
**Time:** 5-15 minutes  
**Data Loss:** Changes since last backup (daily = max 24 hours)

### Scenario 3: Nextcloud Data Loss
**Recovery:**
```bash
# Use AIO restore interface
https://localhost:8090 → Backup & Restore → Select backup → Restore
```
**Time:** 1-4 hours (depends on data size)  
**Data Loss:** Changes since last backup (daily = max 24 hours)

### Scenario 4: Total Server Loss
**Recovery:**
1. Spin up new server
2. Install Docker + Nextcloud AIO
3. Restore Nextcloud from backup (external storage)
4. Deploy ERP code from GitHub
5. Restore database from backup
6. Configure ERP to connect to restored Nextcloud

**Time:** 2-6 hours  
**Data Loss:** Minimal if backups are off-site

---

## Best Practices

### Daily Operations
✅ **Do:**
- Commit code changes to Git daily
- Let Nextcloud handle all document storage
- Monitor Nextcloud disk space
- Check backup logs weekly

❌ **Don't:**
- Don't commit uploaded files to Git
- Don't manually move files from `/uploads/` to Nextcloud
- Don't skip database backups
- Don't store documents outside Nextcloud

### Weekly Maintenance
- [ ] Check Nextcloud backup logs
- [ ] Verify database backup script ran
- [ ] Review storage usage in admin dashboard
- [ ] Test file upload/download in ERP

### Monthly Maintenance
- [ ] Test database restore (on dev copy)
- [ ] Test Nextcloud restore (on dev copy)
- [ ] Review and clean orphaned files
- [ ] Update Nextcloud (via AIO interface)
- [ ] Review storage growth trends

---

## Migration from Local Uploads (If Needed)

If you have existing files in `/uploads/`, migrate them:

```php
<?php
// Run this script once to migrate existing uploads
require_once 'config.php';
require_once 'models/NextcloudClient.php';

$nc = new NextcloudClient();
$uploadDir = BASE_PATH . '/public/uploads/';

// Example: migrate customer documents
$customerDocs = glob($uploadDir . 'customers/*');
foreach ($customerDocs as $file) {
    $customerId = basename(dirname($file));
    $fileName = basename($file);
    
    // Upload to Nextcloud
    $remotePath = "ERP_Documents/customer/{$customerId}/{$fileName}";
    $result = $nc->uploadFile($file, $remotePath);
    
    if ($result['success']) {
        echo "Migrated: {$fileName}\n";
        // Optionally delete local copy
        // unlink($file);
    } else {
        echo "Failed: {$fileName}\n";
    }
}
```

---

## Off-Site Backup (Recommended for Production)

### Option 1: Nextcloud External Storage
Configure Nextcloud to backup to:
- Amazon S3
- Backblaze B2
- Wasabi
- Another server (NFS/SMB)

### Option 2: Database to Cloud
Add to backup script:
```bash
# Upload to S3 (install awscli first)
aws s3 cp "$BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz" \
  s3://your-bucket/mysql-backups/
```

### Option 3: Sync Backups
```bash
# Rsync to remote server
rsync -avz /home/yourusername/backups/ \
  user@backup-server:/backups/erp/
```

---

## Cost Estimate (Production)

| Service | Purpose | Cost |
|---------|---------|------|
| **GitHub** | Code repository | Free (private repos) |
| **VPS/Server** | Host ERP + Nextcloud | $20-100/month |
| **Nextcloud AIO** | Document storage | Free (included) |
| **S3 Backup** | Off-site backup | ~$5-20/month (optional) |
| **Total** | | **$20-120/month** |

---

## Quick Reference

### Git Commands (Code)
```bash
git status                    # Check changes
git add .                     # Stage all changes
git commit -m "message"       # Commit changes
git push                      # Push to GitHub
git pull                      # Pull latest
```

### Database Commands
```bash
# Backup
mysqldump -u rpmbbu -p brickwal_m1_ds > backup.sql

# Restore
mysql -u rpmbbu -p brickwal_m1_ds < backup.sql

# Run migration
mysql -u rpmbbu -p brickwal_m1_ds < database/migrations/XXX.sql
```

### Nextcloud Commands
```bash
# Check status
docker ps | grep nextcloud

# View logs
docker logs nextcloud-aio-mastercontainer

# Restart
docker restart nextcloud-aio-mastercontainer

# Backup now
docker exec nextcloud-aio-mastercontainer \
  php /var/www/docker-aio/php/src/Cron/backup.php
```

---

## Summary

### Your Simple Workflow

1. **Write code** → Commit to Git → Push to GitHub ✅
2. **Users upload docs** → Automatically stored in Nextcloud ✅
3. **Sleep well** → Everything is backed up ✅

**You don't need to:**
- ❌ Manually backup uploaded files
- ❌ Commit documents to Git
- ❌ Worry about file storage

**You DO need to:**
- ✅ Keep pushing code to GitHub (you already do this)
- ✅ Setup automated database backups (one-time, 10 minutes)
- ✅ Enable Nextcloud automatic backups (one-time, 5 minutes)

That's it! 🎉

---

## Support

- **ERP Issues**: Check `README.md`, `WARP.md`
- **Nextcloud Issues**: Check `NEXTCLOUD_INTEGRATION.md`
- **Admin Features**: Check `NEXTCLOUD_ADMIN_GUIDE.md`
- **Nextcloud Docs**: https://docs.nextcloud.com
