# NEXERA AFRICA - Deployment & Migration Guide

## Quick Start: Replace Your Existing Files

**YES - You can directly upload this corrected package to replace your existing files!**

---

## Table of Contents

1. [Pre-Deployment Checklist](#pre-deployment-checklist)
2. [Deployment Methods](#deployment-methods)
3. [Step-by-Step Migration](#step-by-step-migration)
4. [Post-Deployment Setup](#post-deployment-setup)
5. [Security Verification](#security-verification)
6. [Troubleshooting](#troubleshooting)

---

## Pre-Deployment Checklist

Before deploying, ensure you have:

- [ ] **Backup your current site** (files AND database)
- [ ] **Database credentials** (host, username, password, database name)
- [ ] **Pi Network API key** from https://developers.minepi.com
- [ ] **FTP/SFTP access** or cPanel file manager
- [ ] **PHP 7.4+** installed on server (PHP 8.0+ recommended)

---

## Deployment Methods

### Method 1: Direct File Replacement (Recommended for Simple Updates)

This package is designed for **direct replacement** of your existing files:

```
Your Current Structure:          New Corrected Structure:
├── config/                      ├── config/
│   ├── db.php           ❌      │   ├── database.php    ✅ (fixed)
│   ├── env.php                 │   ├── env.php         ✅
│   └── pi.php          ❌      │   └── pi.php          ✅ (fixed)
├── includes/            ❌      ├── templates/          ✅ (new location)
│   ├── header.php              │   ├── header.php      ✅ (XSS fixed)
│   ├── footer.php              │   └── footer.php      ✅
│   └── functions.php           ├── src/                ✅ (new location)
├── register.php        ❌       │   └── functions.php   ✅ (enhanced)
├── index.php          ❌        ├── public/             ✅ (all PHP files)
├── ban_vendor.php     ❌        │   ├── index.php      ✅ (secure)
├── test.php           🗑️       │   ├── register.php   ✅ (secure)
├── test_db_connection.php🗑️    │   ├── ban_vendor.php ✅ (column fixed)
├── test_pi_backend.php 🗘️      │   └── ... (all other pages)
└── ...                           ├── .htaccess          ✅ (NEW!)
                                  ├── .env.example       ✅ (NEW!)
                                  └── .gitignore         ✅ (NEW!)
```

### Method 2: Fresh Install (Clean Deployment)

For a completely fresh installation:

1. Upload entire `Nexera_Corrected` folder contents to your web root
2. Follow [Post-Deployment Setup](#post-deployment-setup) below

---

## Step-by-Step Migration

### Step 1: Backup Everything ⚠️ CRITICAL

```bash
# Via SSH/Terminal:
tar -czvf nexera_backup_$(date +%Y%m%d).tar.gz /path/to/nexera/

# Or use mysqldump for database:
mysqldump -u root -p nexora_db > nexera_db_backup_$(date +%Y%m%d).sql
```

### Step 2: Upload Corrected Files

**Option A: Using FTP/SFTP Client (FileZilla, Cyberduck, etc.)**
1. Connect to your server
2. Navigate to your Nexera directory
3. Upload all files from this package, **overwriting existing files**
4. Preserve folder structure as-is

**Option B: Using cPanel File Manager**
1. Open cPanel → File Manager
2. Navigate to `public_html/nexera/` (or your Nexera folder)
3. Upload the ZIP file
4. Extract it, choosing "Overwrite" when prompted

**Option C: Using Command Line**
```bash
# Upload ZIP, then extract:
cd /path/to/your/web/directory/
unzip -o Nexera_Corrected.zip
# The -o flag overwrites without prompting
```

### Step 3: Set Up Environment Variables

1. Copy the example environment file:
```bash
cp .env.example .env
```

2. Edit `.env` with your actual values:
```bash
nano .env  # or use your preferred editor
```

3. **Required changes in `.env`:**
```env
DB_PASS=YOUR_ACTUAL_DB_PASSWORD_HERE
PI_API_KEY=YOUR_ACTUAL_PI_API_KEY_HERE
SESSION_SECRET=generate_with_php_-r_'echo_bin2hex(random_bytes(16))'
```

### Step 4: Secure Sensitive Files

```bash
# Set proper permissions
chmod 600 .env                    # Only owner can read
chmod 644 .htaccess               # Readable by web server
chmod 755 public/uploads          # Writable by server
chmod -R 755 storage/cache        # Cache directory
chmod -R 755 storage/sessions     # Session storage

# Remove dangerous test files if they exist
rm -f test.php test_db_connection.php test_pi_backend.php validation-key.txt
```

### Step 5: Update Web Server Configuration

**For Apache:** Ensure `.htaccess` is being read:
- Verify `AllowOverride All` is set in your VirtualHost config
- Restart Apache: `sudo service apache2 restart` or via cPanel

**For Nginx:** Add these rules to your server block (`.htaccess` won't work):
```nginx
server {
    # Block sensitive locations
    location ~ /\.env {
        deny all;
        return 404;
    }
    
    location ~ ^/(config|storage|src|templates)/ {
        deny all;
        return 404;
    }
    
    # Disable PHP execution in uploads
    location ~* /uploads/.*\.php$ {
        deny all;
        return 404;
    }
    
    # Security headers
    add_header X-Content-Type-Options "nosniff";
    add_header X-Frame-Options "SAMEORIGIN";
}
```

---

## Post-Deployment Setup

### 1. Database Schema Update

If you need to fix the `is_banned` → `blocked` column issue:

```sql
-- Check current schema:
DESCRIBE users;

-- If 'is_banned' exists and 'blocked' doesn't:
ALTER TABLE users CHANGE COLUMN is_banned blocked TINYINT(1) DEFAULT 0;

-- If both exist, migrate data then drop old column:
UPDATE users SET blocked = is_banned WHERE blocked IS NULL;
ALTER TABLE users DROP COLUMN is_banned;

-- Add missing columns if needed:
ALTER TABLE users 
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    ADD COLUMN IF NOT EXISTS banned_at TIMESTAMP NULL;
```

### 2. Test Critical Functionality

After deployment, verify:

| Feature | How to Test | Expected Result |
|---------|-------------|-----------------|
| Homepage | Visit `/public/index.php` | Loads without errors |
| Registration | Try registering new account | Works, no admin role option |
| Login | Login with existing account | Session created |
| Pi Payment | Complete test transaction | Payment processes |
| Admin Panel | Login as admin, ban user | User gets blocked |
| Language Switch | Change language | Persists across pages |

### 3. Verify Security Fixes

Confirm these vulnerabilities are now fixed:

- [ ] **test.php deleted** → Visit `/test.php` → Should show 404
- [ ] **Credentials removed** → View source of any page → No passwords visible
- [ ] **Error messages safe** → Trigger DB error → Shows generic message only
- [ ] **XSS prevented** → Register with `<script>alert(1)</script>` name → Not executed
- [ ] **CSRF active** → Form submissions require valid token
- [ ] **Admin role secured** → Registration form has no admin option

---

## Troubleshooting

### Issue: "500 Internal Server Error"

**Causes & Solutions:**
1. `.htaccess` syntax error → Check error logs
2. PHP version mismatch → Requires PHP 7.4+
3. Missing dependencies → Ensure `config/env.php` exists

```bash
# Check Apache error log:
tail -f /var/log/apache2/error.log
# or
tail -f /var/log/httpd/error_log
```

### Issue: "Database Connection Failed"

**Check:**
1. `.env` file exists with correct DB credentials
2. MySQL/MariaDB server is running
3. Database `nexora_db` exists
4. User has proper permissions

```bash
# Test connection manually:
mysql -u root -p -h localhost nexora_db
```

### Issue: "Session not working in Pi Browser"

**Solution:** The new structure preserves `SameSite=None; Secure` cookie settings required for Pi Browser iframe context.

### Issue: "Old files still showing"

**Solutions:**
1. Clear browser cache (Ctrl+Shift+R / Cmd+Shift+R)
2. Clear OPcache if enabled:
   ```bash
   sudo service php-fpm restart  # or restart Apache
   ```
3. Check you uploaded to correct directory

---

## Directory Structure Reference

```
Nexera_Corrected/
├── .htaccess              # Apache security rules (UPLOAD THIS!)
├── .env.example           # Environment template (copy to .env)
├── .gitignore             # Git ignore rules
├── README.md              # Project documentation
├── DEPLOYMENT_GUIDE.md    # This file
├── CHANGELOG.md           # Version history
│
├── admin/                 # Admin panel pages
│   ├── index.php
│   ├── manage_users.php
│   ├── manage_listings.php
│   └── view_transactions.php
│
├── config/                # Configuration (NOT publicly accessible)
│   ├── database.php       # DB connection (FIXED - no hardcoded creds)
│   ├── env.php            # Environment loader
│   └── pi.php             # Pi Network config (FIXED - no API key)
│
├── docs/                  # Documentation
│   ├── PI_DATABASE_SCHEMA.sql
│   ├── PI_INTEGRATION_GUIDE.md
│   └── ...
│
├── languages/             # Translation files
│   ├── lang_en.php
│   ├── lang_fr.php
│   ├── lang_rw.php
│   └── lang_sw.php
│
├── public/                # WEB ROOT (only this is public!)
│   ├── api/               # API endpoints
│   │   ├── pi_payment.php
│   │   └── pi_handler.php
│   ├── assets/            # CSS, JS, images
│   │   ├── css/style.css
│   │   └── js/script.js
│   ├── uploads/           # User uploads (PHP disabled here)
│   │   └── .gitkeep
│   ├── index.php          # Homepage (FIXED - no display_errors)
│   ├── register.php       # Registration (FIXED - no admin role)
│   ├── login.php
│   ├── ban_vendor.php     # Ban user (FIXED - uses 'blocked')
│   ├── marketplace.php
│   └── ... (other pages)
│
├── src/                   # Application logic (NOT public)
│   └── functions.php      # Helper functions (ENHANCED)
│
├── storage/               # Private data (NOT public)
│   ├── cache/.gitkeep
│   └── sessions/.gitkeep
│
└── templates/             # HTML templates (NOT public)
    ├── header.php         # Header (FIXED - XSS protection)
    ├── footer.php
    └── errors/
        ├── 403.html
        ├── 404.html
        └── 503.html
```

---

## What Was Fixed?

### 🔴 CRITICAL Fixes (Immediate Security Risk)

| Vulnerability | File | Fix Applied |
|--------------|------|-------------|
| Hardcoded DB password | `config/db.php` | Removed, reads from `.env` |
| Hardcoded Pi API key | `config/pi.php` | Removed, reads from `.env` |
| Exposed test.php | `test.php` | Deleted entirely |
| Error message disclosure | `register.php:80` | Generic error messages |

### 🟠 HIGH Priority Fixes

| Issue | File | Fix Applied |
|-------|------|-------------|
| display_errors=ON | `index.php:2-4` | Removed override |
| XSS in output | `header.php:102` | Added htmlspecialchars() |
| Admin privilege escalation | `register.php:147` | Role selection removed |
| Wrong SQL column | `ban_vendor.php:14` | Changed to `blocked` |

### 🟡 Infrastructure Improvements

| Addition | Purpose |
|----------|---------|
| `.htaccess` | Security headers, directory protection, upload security |
| `.env.example` | Template for secure credential management |
| `.gitignore` | Prevents secrets in version control |
| Rate limiting | Prevents brute-force attacks |
| Password strength indicator | Better user experience |

---

## Need Help?

If you encounter issues during deployment:

1. **Check the logs**: `logs/php_errors.log`
2. **Verify file permissions**: Ensure `.env` is `600`
3. **Test incrementally**: Deploy one fix at a time if needed
4. **Rollback**: Restore from backup if critical issues arise

---

**Last Updated:** 2026-01-15  
**Version:** 2.0 (Security Release)  
**Compatible With:** PHP 7.4+, MySQL 5.7+/MariaDB 10.3+
