# Production Deployment Guide

## Overview
After pushing code to GitHub via the System Scripts interface, you need to:
1. Pull code updates on production
2. Run any pending database migrations
3. Verify deployment

## Quick Deployment (Automated)

### Option 1: Use the Deployment Script ✅ RECOMMENDED
```bash
# Run from your local dev environment
cd /Users/rpmbbu/LocalPHPStorm/m1_erp_web
chmod +x scripts/deploy_to_production.sh

# Review what will be deployed
./scripts/deploy_to_production.sh

# Or deploy immediately
./scripts/deploy_to_production.sh --execute
```

**What it does:**
- ✅ Checks your local git is in sync with GitHub
- ✅ Lists all pending migrations
- ✅ Creates automatic database backup on production
- ✅ Pulls latest code from GitHub
- ✅ Runs only migrations that haven't been applied yet
- ✅ Tracks migration status in `migration_log` table
- ✅ Verifies deployment success

**Before first use:**
Edit `scripts/deploy_to_production.sh` line 24 and set the correct production path:
```bash
PROD_PATH="/var/www/html/m1_erp_web"  # or wherever your production is
```

---

## Manual Deployment (Step-by-Step)

### Step 1: Push to GitHub
1. Navigate to `http://localhost/admin/system-scripts`
2. Click **Version Control** tab
3. Use **Push to GitHub** script
4. Verify success

### Step 2: SSH to Production
```bash
ssh mavrixone@merph.mavrixone
# Password: xyz8468RPMerkuri123!
```

### Step 3: Backup Database
```bash
cd /path/to/production/m1_erp_web
mkdir -p backups
mysqldump -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds > backups/backup_$(date +%Y%m%d_%H%M%S).sql
```

### Step 4: Pull Latest Code
```bash
cd /path/to/production/m1_erp_web
git fetch origin
git pull origin main
```

### Step 5: Check Which Migrations Need Running
```bash
# See what migrations you have locally
ls database/migrations/*.sql | grep -E "^database/migrations/[0-9]+" | sort -V

# On production, check which have been applied
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds -e "
    SELECT migration_number, migration_file, applied_at 
    FROM migration_log 
    WHERE status='success' 
    ORDER BY migration_number DESC 
    LIMIT 10;"
```

### Step 6: Run Pending Migrations
```bash
# Run each migration that hasn't been applied yet
# The script will automatically log to migration_log table

cd database/migrations

# Example: Run migration 1016
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds < 1016_enhance_sales_orders.sql

# Repeat for each pending migration in order
```

### Step 7: Verify
```bash
# Check migration log
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds -e "
    SELECT COUNT(*) as total_migrations FROM migration_log WHERE status='success';
    SELECT migration_file, applied_at FROM migration_log ORDER BY applied_at DESC LIMIT 5;"

# Test the application
curl https://merph.mavrixone/
```

---

## Migration Tracking System

### How It Works
Since migration **1006**, all migrations are automatically tracked in the `migration_log` table:

```sql
CREATE TABLE migration_log (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    migration_number INT NOT NULL,
    migration_file VARCHAR(255) NOT NULL,
    description TEXT NULL,
    applied_by INT UNSIGNED NULL,
    applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    execution_time_ms INT NULL,
    status ENUM('success', 'failed', 'rolled_back') DEFAULT 'success',
    error_message TEXT NULL
);
```

### Check Migration Status
```bash
# On production server
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds

# List all applied migrations
SELECT migration_number, migration_file, applied_at, status 
FROM migration_log 
ORDER BY migration_number;

# Find migrations that failed
SELECT * FROM migration_log WHERE status='failed';

# Get the last 10 migrations
SELECT migration_file, applied_at 
FROM migration_log 
ORDER BY applied_at DESC 
LIMIT 10;
```

### Compare Dev vs Production
```bash
# On your dev machine
ls database/migrations/*.sql | wc -l

# On production
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds -e \
    "SELECT COUNT(*) FROM migration_log WHERE status='success';"
```

---

## Troubleshooting

### Migration Already Applied (Error)
If a migration file already made changes and fails on re-run:
```sql
-- Check if table/column exists first
SELECT * FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA='brickwal_m1_ds' 
AND TABLE_NAME='your_table' 
AND COLUMN_NAME='your_column';
```

All migrations should use `IF NOT EXISTS` / `IF EXISTS` to be idempotent.

### Migration Failed Halfway
```bash
# 1. Restore from backup
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds < backups/backup_20250120_143000.sql

# 2. Fix the migration file
# 3. Re-run it

# 4. Mark as failed in log
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds -e "
    UPDATE migration_log 
    SET status='rolled_back' 
    WHERE migration_file='1016_problematic_migration.sql';"
```

### Check What Changed in Latest Push
```bash
# On production
git log -1 --stat
git diff HEAD~1 HEAD database/migrations/
```

### Rollback Last Migration
```bash
# 1. Restore from backup
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds < backups/backup_TIMESTAMP.sql

# 2. Mark as rolled back
mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds -e "
    UPDATE migration_log 
    SET status='rolled_back' 
    WHERE migration_file='problematic_migration.sql';"

# 3. Revert code
git revert HEAD
git push origin main
```

---

## Best Practices

### ✅ DO:
1. **Always** use the deployment script for consistency
2. **Always** create database backup before migrations
3. **Always** test migrations on dev/staging first
4. **Always** run migrations in order (sorted by number)
5. **Always** verify deployment after completion
6. Use System Scripts interface for git operations
7. Check migration_log table to see what's been applied

### ❌ DON'T:
1. Skip database backups
2. Run migrations out of order
3. Edit migrations that have already been applied to production
4. Delete from migration_log table (use status='rolled_back' instead)
5. Manually commit/push without System Scripts (breaks version tracking)

---

## Files Reference

| File | Purpose |
|------|---------|
| `scripts/deploy_to_production.sh` | Automated deployment script |
| `database/migrations/*.sql` | Database migration files |
| `database/README.md` | Migration creation guide |
| `DEPLOYMENT_GUIDE.md` | This file |

---

## Quick Commands

```bash
# Check local migrations
ls database/migrations/*.sql | grep -E "^database/migrations/[0-9]+" | sort -V | tail -10

# Count local migrations
ls database/migrations/*.sql | grep -E "^database/migrations/[0-9]+" | wc -l

# Check what's in latest git push
git log -1 --name-status

# Check production migration status
ssh mavrixone@merph.mavrixone "mysql -u rpmbbu -pz8468RPMerkuri123! brickwal_m1_ds -e 'SELECT COUNT(*) FROM migration_log WHERE status=\"success\"'"

# Full deployment (automated)
./scripts/deploy_to_production.sh --execute
```

---

## Support

If you encounter issues:
1. Check the backup file location (script shows this)
2. Review migration_log table for failures
3. Check production server logs
4. Restore from backup if needed
5. Fix migration file and re-run

**Database Backups Location:** `production_path/backups/`  
**Migration Log Table:** `brickwal_m1_ds.migration_log`
