# 🚀 Backend Deployment Guide

## Prerequisites
- Linux server (Ubuntu/Debian recommended)
- MySQL/MariaDB installed
- Node.js 16+ installed
- phpMyAdmin (optional, for GUI database management)
- Domain name (optional, but recommended)

---

## 📋 Step-by-Step Deployment

### 1. Database Setup

#### Option A: Using phpMyAdmin (Easiest)

1. **Login to phpMyAdmin** on your server
2. **Click "Import"** tab
3. **Choose file**: Select `faceml_database.sql`
4. **Click "Go"** to import
5. ✅ Database `faceml_db` will be created with all tables

#### Option B: Using MySQL Command Line

```bash
# Login to MySQL
mysql -u root -p

# Create database
CREATE DATABASE faceml_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Exit MySQL
exit

# Import the SQL file
mysql -u root -p faceml_db < faceml_database.sql
```

### 2. Verify Database Import

Login to MySQL and verify:
```bash
mysql -u root -p

USE faceml_db;

-- Check tables
SHOW TABLES;

-- Should show:
-- +----------------------+
-- | Tables_in_faceml_db  |
-- +----------------------+
-- | attendance           |
-- | branches             |
-- | shops               |
-- | staff               |
-- | users               |
-- | work_sessions       |
-- +----------------------+

-- Check default admin (optional)
SELECT email, role FROM users;
```

### 3. Upload Backend Files

```bash
# On your server
cd /var/www  # or your preferred directory

# Clone or upload your backend folder
# If using git:
git clone your-repo-url
cd faceml/backend

# Or upload via FTP/SFTP the entire backend folder
```

### 4. Install Dependencies

```bash
cd /var/www/faceml/backend

# Install Node modules
npm install
```

### 5. Configure Environment Variables

Create `.env` file in backend directory:

```bash
nano .env
```

Add the following (update with your actual values):

```env
# Server Configuration
NODE_ENV=production
PORT=3000

# Database Configuration
DB_HOST=localhost
DB_USER=your_mysql_username
DB_PASSWORD=your_mysql_password
DB_NAME=faceml_db
DB_PORT=3306

# JWT Configuration
JWT_SECRET=your-super-secure-random-string-min-32-characters-long

# Super Admin Default Credentials
SUPER_ADMIN_EMAIL=admin@faceml.com
SUPER_ADMIN_PASSWORD=Admin@123

# CORS (optional - for specific frontend domain)
# ALLOWED_ORIGINS=https://yourfrontend.com
```

**Important**: Generate a strong JWT_SECRET:
```bash
# Generate random string (32+ characters)
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

### 6. Initialize/Update Super Admin Password

Run the initialization script to create proper password hash:

```bash
cd /var/www/faceml/backend
node scripts/initDatabase.js
```

This will:
- ✅ Verify database connection
- ✅ Create/update super admin with proper bcrypt password hash
- ✅ Display login credentials

### 7. Test Backend Locally

```bash
# Start server
node server.js

# Or use PM2 (recommended for production)
npm install -g pm2
pm2 start server.js --name faceml-backend
```

Test the API:
```bash
# Health check
curl http://localhost:3000/health

# Should return:
# {"status":"OK","timestamp":"...","environment":"production"}
```

### 8. Configure Nginx (Recommended for Production)

Create Nginx configuration:

```bash
sudo nano /etc/nginx/sites-available/faceml-api
```

Add this configuration:

```nginx
server {
    listen 80;
    server_name api.yourdomain.com;  # Change to your domain

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # Increase timeout for large face embedding uploads
        proxy_read_timeout 300;
        proxy_connect_timeout 300;
        proxy_send_timeout 300;
    }

    # Increase client body size for face embeddings
    client_max_body_size 50M;
}
```

Enable the site:
```bash
sudo ln -s /etc/nginx/sites-available/faceml-api /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### 9. Setup SSL (Highly Recommended)

```bash
# Install Certbot
sudo apt install certbot python3-certbot-nginx

# Get SSL certificate
sudo certbot --nginx -d api.yourdomain.com
```

### 10. Setup PM2 for Auto-Start

```bash
# Start backend with PM2
cd /var/www/faceml/backend
pm2 start server.js --name faceml-backend

# Configure PM2 to start on system boot
pm2 startup
pm2 save

# View logs
pm2 logs faceml-backend

# Monitor
pm2 monit
```

---

## 🧪 Testing Your Deployment

### 1. Test Health Endpoint
```bash
curl https://api.yourdomain.com/health
```

### 2. Test Login
```bash
curl -X POST https://api.yourdomain.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@faceml.com",
    "password": "Admin@123"
  }'
```

Should return JWT token.

### 3. Update Flutter App

In your Flutter app (`lib/services/api_service.dart`), update the base URL:

```dart
class ApiService {
  static const String baseUrl = 'https://api.yourdomain.com/api';
  // ... rest of code
}
```

---

## 🔒 Security Checklist

- [ ] Changed default super admin password
- [ ] Using strong JWT_SECRET (32+ characters)
- [ ] Enabled SSL/HTTPS
- [ ] Configured firewall (allow only ports 80, 443, 22)
- [ ] MySQL only accessible from localhost
- [ ] Created MySQL user with limited privileges (not root)
- [ ] Regular database backups enabled
- [ ] PM2 running in production mode
- [ ] Nginx configured with security headers
- [ ] Rate limiting enabled (optional)

---

## 🔧 Common Issues & Solutions

### Database Connection Failed
```bash
# Check MySQL is running
sudo systemctl status mysql

# Check credentials in .env file
# Ensure MySQL user has permissions on faceml_db
```

### Port Already in Use
```bash
# Check what's using port 3000
sudo lsof -i :3000

# Kill process or change PORT in .env
```

### PM2 Not Starting
```bash
# Check logs
pm2 logs faceml-backend --lines 50

# Restart
pm2 restart faceml-backend
```

### Large File Upload Fails
- Increase `client_max_body_size` in Nginx
- Increase `limit` in `server.js` (already set to 50mb)

---

## 📊 Database Backup

### Manual Backup
```bash
# Backup database
mysqldump -u root -p faceml_db > backup_$(date +%Y%m%d_%H%M%S).sql

# Compress backup
gzip backup_*.sql
```

### Automated Daily Backup
```bash
# Create backup script
nano ~/backup-faceml.sh
```

Add:
```bash
#!/bin/bash
BACKUP_DIR="/var/backups/faceml"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
mysqldump -u root -p'your_password' faceml_db > $BACKUP_DIR/backup_$TIMESTAMP.sql
gzip $BACKUP_DIR/backup_$TIMESTAMP.sql
# Keep only last 7 days
find $BACKUP_DIR -name "backup_*.sql.gz" -mtime +7 -delete
```

Make executable and add to crontab:
```bash
chmod +x ~/backup-faceml.sh
crontab -e

# Add this line (runs daily at 2 AM)
0 2 * * * ~/backup-faceml.sh
```

---

## 📱 Update Flutter App Configuration

After deployment, update your Flutter app:

1. **Update API URL** in `lib/services/api_service.dart`:
```dart
static const String baseUrl = 'https://api.yourdomain.com/api';
```

2. **Rebuild the app**:
```bash
flutter clean
flutter pub get
flutter build apk  # For Android
flutter build ios  # For iOS
```

---

## 🎉 Deployment Complete!

Your backend is now running in production. Access points:

- **API Base URL**: `https://api.yourdomain.com/api`
- **Health Check**: `https://api.yourdomain.com/health`
- **Admin Login**:
  - Email: admin@faceml.com
  - Password: Admin@123 (Change immediately!)

---

## 📞 Need Help?

- Check PM2 logs: `pm2 logs faceml-backend`
- Check Nginx logs: `sudo tail -f /var/log/nginx/error.log`
- Check MySQL logs: `sudo tail -f /var/log/mysql/error.log`

---

## 📝 Maintenance Commands

```bash
# Restart backend
pm2 restart faceml-backend

# View logs
pm2 logs faceml-backend

# Monitor performance
pm2 monit

# Update backend
cd /var/www/faceml/backend
git pull
npm install
pm2 restart faceml-backend

# Restart Nginx
sudo systemctl restart nginx

# Restart MySQL
sudo systemctl restart mysql
```

Good luck with your deployment! 🚀

