# 🚀 Production Deployment - DNS & Router Setup Guide

## System Information You'll Need

```
Your Public IP (Internet):     78.137.202.90
Your Local IP (PC):            192.168.10.67
Your Domain:                   sales.globalerc.pt
Current DNS Points To:         94.46.169.199 (WRONG - hosting provider)
New DNS Should Point To:       78.137.202.90 (CORRECT - your public IP)
Ports to Forward:              80 (HTTP), 443 (HTTPS)
```

---

## STEP 1: Update DNS at Your Domain Registrar

> ⏱️ **Time:** 5 minutes to update + 5-15 minutes to propagate globally

### Where to Make Changes

You need to access your **domain registrar** (whoever you bought/manage `sales.globalerc.pt` from).

**Common registrars:**
- GoDaddy
- Namecheap
- Domains.com
- Registrar.pt (Portuguese)
- GitHub (if using GitHub Pages)
- Your hosting provider's control panel

### What to Change

**Find your DNS settings and look for:**
- **A Record** for `sales` or `sales.globalerc.pt`

**OLD VALUE (DELETE or CHANGE):**
```
Type: A
Name: sales (or blank if it's the main domain)
Value: 94.46.169.199
TTL: 3600 (or whatever is shown)
```

**NEW VALUE (SET TO THIS):**
```
Type: A
Name: sales (or blank if pointing main domain)
Value: 78.137.202.90
TTL: 3600 (keep same)
```

### Step-by-Step Example: GoDaddy

1. Go to **https://godaddy.com** → Sign In
2. Click **My Products**
3. Find `globalerc.pt` → Click **Manage DNS**
4. Find the **A Record** with value `94.46.169.199`
5. Click **Edit** (pencil icon)
6. Change the value to `78.137.202.90`
7. Click **Save**
8. Wait 5-15 minutes for DNS propagation

### Step-by-Step Example: Namecheap

1. Go to **https://namecheap.com** → Sign In
2. Click **Domain List**
3. Find `globalerc.pt` → Click **Manage**
4. Go to **Advanced DNS** tab
5. Find **A Record** with `94.46.169.199`
6. Click **Edit** icon
7. Change the value to `78.137.202.90`
8. Click **Save**
9. Wait 5-15 minutes

### Verify DNS Updated

**In PowerShell, check if DNS propagated:**
```powershell
# Check if DNS now points to your public IP
nslookup sales.globalerc.pt

# Expected output:
# Name:    sales.globalerc.pt
# Address: 78.137.202.90
```

If it still shows `94.46.169.199`, DNS hasn't propagated yet. Wait 5-10 min and try again.

---

## STEP 2: Configure Router Port Forwarding

> ⏱️ **Time:** 10-15 minutes

### Access Your Router

1. **Find your router's IP address:**
   ```powershell
   ipconfig /all | findstr "Gateway"
   ```
   Usually shows `192.168.1.1` or `192.168.10.1`

2. **Open browser and go to:**
   ```
   http://192.168.10.1
   (Replace .1 with whatever ipconfig shows)
   ```

3. **Login with:**
   - Username: `admin` (or whatever you set)
   - Password: (check router sticker, or reset if forgotten)

### Configure Port Forwarding

**Goal:** Forward external ports 80/443 → your PC (192.168.10.67:80/443)

#### Option A: Simple Setup (Recommended First)

Look for: **"Port Forwarding"** or **"Virtual Server"** menu

| External Port | Internal IP | Internal Port | Protocol |
|---------------|-------------|---------------|----------|
| 80           | 192.168.10.67 | 80            | TCP      |
| 443          | 192.168.10.67 | 443           | TCP      |

**Example in common routers:**

**TP-Link / Archer:**
1. Go to **NAT Forwarding** → **Port Forwarding**
2. Click **Add New**
3. Fill in:
   - **External Port:** 80
   - **Internal IP:** 192.168.10.67
   - **Internal Port:** 80
   - **Protocol:** TCP
4. Click **Add**
5. Repeat for port 443

**Netgear:**
1. Go to **Advanced** → **Port Forwarding/Triggering**
2. Click **Port Forwarding**
3. Fill in:
   - **Service Name:** NginxHTTP
   - **External Port Start/End:** 80
   - **Internal Port Start/End:** 80
   - **IP Address:** 192.168.10.67
   - **Protocol:** TCP
4. Click **Add**
5. Repeat for port 443

**Asus:**
1. Go to **NAT Passthrough** or **Virtual Server**
2. Click **Add Rule**
3. Fill in:
   - **IP Address:** 192.168.10.67
   - **Port:** 80
   - **Protocol:** TCP
4. Click **Apply**
5. Repeat for port 443

#### Option B: DMZ (Alternative - Less Secure)

If router doesn't have Port Forwarding, use **DMZ:**

1. Find **DMZ** or **Demilitarized Zone**
2. Enable it
3. Set **DMZ IP** to `192.168.10.67`
4. Apply

**⚠️ Warning:** DMZ exposes your PC to internet. Use Port Forwarding if possible.

### Save Router Changes

- Click **Save** or **Apply** (important!)
- Router may restart (normal)
- Wait 1-2 minutes

### Check Router Configuration

**In PowerShell, verify it worked:**
```powershell
# Check if ports are listening on your public IP
# (This may timeout if firewall blocks - that's okay for now)
Test-NetConnection -ComputerName 78.137.202.90 -Port 80 -InformationLevel Detailed

# Should eventually show "Open" or successful connection
```

---

## STEP 3: Configure Windows Firewall

> ⏱️ **Time:** 5 minutes

**Allow ports 80 and 443 through Windows Firewall:**

```powershell
# Run as Administrator

# Port 80 (HTTP)
New-NetFirewallRule -DisplayName "Sales Dashboard HTTP" `
  -Direction Inbound -Protocol TCP -LocalPort 80 `
  -Action Allow -ErrorAction SilentlyContinue

# Port 443 (HTTPS)
New-NetFirewallRule -DisplayName "Sales Dashboard HTTPS" `
  -Direction Inbound -Protocol TCP -LocalPort 443 `
  -Action Allow -ErrorAction SilentlyContinue

# Verify they were added
Get-NetFirewallRule -DisplayName "Sales Dashboard*"
```

---

## STEP 4: Install Nginx

> ⏱️ **Time:** 5 minutes

Nginx is the reverse proxy that handles HTTPS and forwards to Flask.

```powershell
# Install Nginx via Chocolatey
choco install nginx -y

# Start Nginx
cd C:\nginx
.\nginx.exe

# Verify it's running
netstat -an | findstr :443
# Should show:  LISTENING on 0.0.0.0:443
```

---

## STEP 5: Get SSL Certificate

> ⏱️ **Time:** 15 minutes

You need an SSL certificate for HTTPS. Use **ZeroSSL** (free):

### Get Free Certificate from ZeroSSL

1. Go to **https://zerossl.com**
2. Click **Free SSL Certificate**
3. Enter: `sales.globalerc.pt`
4. Click **Next**
5. Choose **Email Validation**
6. Check your email, click validation link
7. Click **Download Certificate** (PEM format)
8. Extract the ZIP file

### Install Certificate

You'll get 3 files:
- `certificate.crt`
- `private.key`
- `ca_bundle.crt`

**Copy them to Nginx:**
```powershell
# Create certificate directory
mkdir C:\nginx\certs -ErrorAction SilentlyContinue

# Copy certificate files
Copy-Item "certificate.crt" "C:\nginx\certs\" -Force
Copy-Item "private.key" "C:\nginx\certs\" -Force
Copy-Item "ca_bundle.crt" "C:\nginx\certs\" -Force

# Update nginx.conf to use them
notepad C:\nginx\conf\nginx.conf
```

**In nginx.conf, find the HTTPS section and update:**
```nginx
server {
    listen 443 ssl;
    server_name sales.globalerc.pt;
    
    ssl_certificate C:/nginx/certs/certificate.crt;
    ssl_certificate_key C:/nginx/certs/private.key;
    
    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# Also redirect HTTP to HTTPS
server {
    listen 80;
    server_name sales.globalerc.pt;
    return 301 https://$server_name$request_uri;
}
```

**Test Nginx configuration:**
```powershell
cd C:\nginx
.\nginx.exe -t

# Should output: "successful"
```

---

## STEP 6: Update Google OAuth

> ⏱️ **Time:** 5 minutes

You need to add `https://sales.globalerc.pt/oauth2callback` to your Google OAuth app:

1. Go to **Google Cloud Console**
2. Find your project (Sales Dashboard)
3. Go to **APIs & Services** → **OAuth 2.0 Client IDs**
4. Click your Web Application
5. Under **Authorized redirect URIs**, add:
   ```
   https://sales.globalerc.pt/oauth2callback
   ```
6. Click **Save**

---

## STEP 7: Start Production Services

> ⏱️ **Time:** 2 minutes

**Terminal 1 - Start Flask (PROD mode):**
```powershell
cd "C:\Users\Tiago Rebelo\Desktop\Globale RC\2-Vibe Coding\Sales Dashboard App_VScode"
.\run_prod.ps1
```

**Terminal 2 - Start Nginx:**
```powershell
cd C:\nginx
.\nginx.exe
```

**Verify both are running:**
```powershell
Get-Process python, nginx
Get-NetTCPConnection -LocalPort 443, 5000 -ErrorAction SilentlyContinue
```

---

## STEP 8: Test Production

> ⏱️ **Time:** 5 minutes

### Test 1: From Your Local PC

```powershell
# Test HTTPS connection
$r = Invoke-WebRequest -Uri "https://sales.globalerc.pt" -UseBasicParsing
"Status: $($r.StatusCode)"

# Expected output: Status: 200
```

### Test 2: From Another Device

1. **Get a second device** (phone, tablet, or different computer)
2. **Connect to different WiFi** (not home WiFi - use mobile hotspot)
3. **Open browser and go to:**
   ```
   https://sales.globalerc.pt/dashboard
   ```
4. **You should see:**
   - Green padlock (SSL certificate valid)
   - Dashboard loads
   - Login button works

### Test 3: Check SSL Certificate

In browser, click padlock icon:
- Should show: "Connection is secure"
- Certificate for: `sales.globalerc.pt`
- Issued by: ZeroSSL

---

## Troubleshooting

### ❌ "Connection Refused" or "Not Responding"

**Check 1: Is DNS updated?**
```powershell
nslookup sales.globalerc.pt
# Must show: 78.137.202.90
```

**Check 2: Is port forwarding working?**
```powershell
Test-NetConnection -ComputerName 78.137.202.90 -Port 443
# Should show "TcpTestSucceeded: True"
```

**Check 3: Is Nginx running?**
```powershell
Get-Process nginx
Get-NetTCPConnection -LocalPort 443
# Should show state: LISTENING
```

**Check 4: Is Flask running?**
```powershell
Get-Process python
Get-NetTCPConnection -LocalPort 5000
# Should show 127.0.0.1:5000 LISTENING
```

### ❌ "Certificate Error" or "Untrusted Certificate"

**Issue:** SSL certificate not properly installed

**Fix:**
```powershell
# 1. Stop Nginx
taskkill /F /IM nginx.exe

# 2. Verify certificate files exist
Test-Path C:\nginx\certs\certificate.crt
Test-Path C:\nginx\certs\private.key

# 3. Update nginx.conf with correct paths (use forward slashes)
# 4. Restart Nginx
cd C:\nginx
.\nginx.exe
```

### ❌ "Timeout" when Testing

**Issue:** Port forwarding not working

**Fix:**
1. Double-check port forwarding in router:
   - External: 80/443
   - Internal IP: 192.168.10.67
   - Internal Port: 80/443
2. Restart router
3. Check Windows Firewall rules are in place
4. Try pinging router from another device on network

### ❌ "DNS Still Points to Old IP"

**Issue:** DNS propagation hasn't completed

**Fix:**
```powershell
# Clear DNS cache
ipconfig /flushdns

# Wait 5 minutes, then test again
nslookup sales.globalerc.pt

# Check from external service
# Go to: https://www.nslookup.io/?query=sales.globalerc.pt
```

---

## Full Deployment Checklist

Print this and check off as you go:

- [ ] **DNS Updated** (A record: sales → 78.137.202.90)
- [ ] **DNS Propagated** (verified with `nslookup`)
- [ ] **Router Port Forwarding Set** (80 → 192.168.10.67:80, 443 → 192.168.10.67:443)
- [ ] **Windows Firewall Rules Added** (ports 80, 443 allowed)
- [ ] **Nginx Installed** (`C:\nginx\nginx.exe` works)
- [ ] **SSL Certificate Obtained** (from ZeroSSL)
- [ ] **Certificate Files Copied** (to `C:\nginx\certs\`)
- [ ] **nginx.conf Updated** (with certificate paths and proxy settings)
- [ ] **Google OAuth Updated** (redirect URI added)
- [ ] **Flask PROD Started** (`.\run_prod.ps1`)
- [ ] **Nginx Started** (`cd C:\nginx; .\nginx.exe`)
- [ ] **HTTPS Test Passed** (https://sales.globalerc.pt returns 200)
- [ ] **External Test Passed** (accessed from different network)
- [ ] **Certificate Valid** (green padlock in browser)

---

## Quick Reference: Exact Commands

**After setup is done, use these to restart:**

```powershell
# Terminal 1: Start Flask PROD
Get-Process python -ErrorAction SilentlyContinue | Stop-Process -Force
Start-Sleep -Seconds 2
.\run_prod.ps1

# Terminal 2: Start Nginx  
taskkill /F /IM nginx.exe 2>$null
Start-Sleep -Seconds 2
cd C:\nginx
.\nginx.exe
```

**Daily Verification:**
```powershell
# Check services are running
Get-Process python, nginx

# Test HTTPS from local PC
Invoke-WebRequest -Uri "https://sales.globalerc.pt" -UseBasicParsing | Select-Object StatusCode
```

---

## Support & Next Steps

**If you get stuck:**
1. Check Troubleshooting section above
2. Verify all checklist items are completed
3. Check error logs:
   - `C:\nginx\logs\error.log`
   - Terminal output from `.\run_prod.ps1`

**Once working:**
- Share `https://sales.globalerc.pt` with sales team
- They can login with their Google/Microsoft accounts
- Everything is now live!

---

**Ready to start? Begin with STEP 1: Update DNS**
