# 🚀 JM3 Deployment Guide
## Shared Hosting: `jmtree.wundanyimbale.co.ke`

---

## 📋 Pre-Deployment Checklist

### **1. Domain & Hosting Setup (First!)**

**What you need:**
- [ ] Shared hosting account (cPanel recommended)
- [ ] Domain: `wundanyimbale.co.ke`
- [ ] Ability to create subdomains

**Steps:**

1. **Create Subdomain in cPanel:**
   - Log in to cPanel → Addon Domains (or Subdomains)
   - Create: `jmtree.wundanyimbale.co.ke`
   - Point to a new folder: `/public_html/jmtree`
   - Wait 5-10 minutes for DNS propagation

2. **Verify DNS:**
   ```bash
   ping jmtree.wundanyimbale.co.ke
   ```

---

## 🔧 Production Configuration

### **2. Update Settings for Production**

Edit `treetracker/settings.py`:

```python
import os
from dotenv import load_dotenv

load_dotenv()  # Load from .env file

# Production settings
DEBUG = False
ALLOWED_HOSTS = ['jmtree.wundanyimbale.co.ke', 'www.jmtree.wundanyimbale.co.ke']

# Secret key (use a strong random key)
SECRET_KEY = os.getenv('SECRET_KEY', 'your-secure-random-key-here')

# Database - SQLite is fine for shared hosting
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Static files (important!)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Media files (uploaded photos)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Security
SECURE_SSL_REDIRECT = True  # Force HTTPS
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_BROWSER_XSS_FILTER = True

# Email - Resend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.resend.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'resend'  # Fixed username
EMAIL_HOST_PASSWORD = os.getenv('RESEND_API_KEY')
DEFAULT_FROM_EMAIL = 'webappclappdev@gmail.com'
```

### **3. Create .env File (Production)**

Create `treetracker/.env`:

```env
SECRET_KEY=your-very-secure-random-key-change-this-in-production
DEBUG=False
ALLOWED_HOSTS=jmtree.wundanyimbale.co.ke
RESEND_API_KEY=re_gNgQLTZA_NxLkr6XYgngMQp4KgQw3Y4G5
```

---

## 📦 Deploy Code

### **4. Upload to Shared Hosting**

**Option A: Via cPanel File Manager**
1. In cPanel, go to File Manager
2. Navigate to `/public_html/jmtree`
3. Upload all files (exclude `.git`, `venv`, `__pycache__`)

**Option B: Via FTP**
```bash
# From your local machine
ftp your-hosting-ftp.com
# Use your cPanel credentials
# Upload everything to: /public_html/jmtree
```

**Option C: Via SSH (if available)**
```bash
ssh user@your-hosting.com
cd /public_html/jmtree
git clone https://your-repo-url.git .
```

---

## 🐍 Python Environment Setup

### **5. Install Python Packages**

In cPanel Terminal (or SSH):

```bash
cd /public_html/jmtree

# Create virtual environment
python3 -m venv venv

# Activate it
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt
```

---

## 🗄️ Database & Migrations

### **6. Run Migrations**

```bash
cd /public_html/jmtree
source venv/bin/activate

# Create database
python manage.py migrate

# Collect static files
python manage.py collectstatic --noinput
```

### **7. Create Admin User**

```bash
python manage.py createsuperuser
# Follow prompts for username, email, password
```

---

## 🌐 Web Server Configuration

### **8. Configure Apache (.htaccess)**

Most shared hosting uses Apache + mod_wsgi. Create `/public_html/jmtree/.htaccess`:

```apache
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ app.wsgi/$1 [QSA,L]
</IfModule>
```

### **9. Create WSGI Entry Point**

Create `/public_html/jmtree/app.wsgi`:

```python
import sys
import os

# Add the project directory to the sys.path
sys.path.insert(0, '/home/username/public_html/jmtree')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'treetracker.settings')

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
```

### **10. Configure via cPanel**

1. Go to cPanel → Python Apps (or Setup Python App)
2. Create new Python app
3. Set Python version to 3.9+ (if available)
4. App root: `/public_html/jmtree`
5. Startup script: `app.wsgi`
6. Interpreter: The venv python

---

## ✅ Final Checks

### **11. Verify Everything Works**

```bash
# Check migrations ran
cd /public_html/jmtree
source venv/bin/activate
python manage.py showmigrations

# Check static files collected
ls staticfiles/
# Should see: admin/ trees/ css/ js/ images/
```

### **12. Test the Website**

Visit: `https://jmtree.wundanyimbale.co.ke`

Should see:
- ✅ Welcome page with JM3 logo
- ✅ Get Started button works
- ✅ SSL certificate (green lock icon)
- ✅ No console errors (F12)

### **13. Test Admin Panel**

Visit: `https://jmtree.wundanyimbale.co.ke/admin`
- Log in with superuser credentials created in step 7
- Verify you can see the data

---

## 🚨 Troubleshooting

### **Issue: Static files not loading (404)**

**Solution:**
```bash
python manage.py collectstatic --noinput --clear
```

### **Issue: Permission denied on database**

**Solution:**
```bash
chmod 755 /public_html/jmtree
chmod 644 /public_html/jmtree/db.sqlite3
```

### **Issue: Email OTP not sending**

**Solution:**
- Verify RESEND_API_KEY in `.env` is correct
- Check cPanel → Email → Email Deliverability

### **Issue: 500 Error / White page**

**Solution:**
1. Check error log: `tail -50 /home/username/public_html/jmtree/error.log`
2. Check Apache logs: `tail -50 /var/log/apache2/error.log`
3. Verify `SECRET_KEY` in `.env`

---

## 📱 Post-Deployment

### **14. Enable HTTPS (Free via Let's Encrypt)**

1. In cPanel → AutoSSL
2. Click "Check & Install"
3. Wait 5 minutes
4. Verify: https://jmtree.wundanyimbale.co.ke

### **15. Backup Database**

```bash
# Create backup
python manage.py dumpdata > backup.json

# Download to your machine for safety
```

### **16. Monitor & Maintain**

- Check disk space monthly (photos/uploads grow)
- Update Django security patches
- Monitor error logs

---

## 📊 Production Checklist Summary

- [ ] Subdomain created: `jmtree.wundanyimbale.co.ke`
- [ ] Code uploaded to `/public_html/jmtree`
- [ ] Virtual environment created & activated
- [ ] `requirements.txt` installed
- [ ] `.env` file created with production values
- [ ] `python manage.py migrate` run
- [ ] `python manage.py collectstatic` run
- [ ] Superuser created
- [ ] `.htaccess` configured
- [ ] `app.wsgi` created
- [ ] Python app configured in cPanel
- [ ] HTTPS enabled via Let's Encrypt
- [ ] Website tested at https://jmtree.wundanyimbale.co.ke
- [ ] Admin panel working at /admin
- [ ] Email OTP tested (send test email)

---

## 🎯 What Users Will See

1. **Welcome page** → `https://jmtree.wundanyimbale.co.ke`
2. **Sign up** → Creates account, sends OTP via email
3. **Dashboard** → Add trees, view tasks
4. **Admin** → `https://jmtree.wundanyimbale.co.ke/admin`

---

**Questions?** Check Django deployment docs: https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
