# Abbas FIT - Complete Deployment Guide

This guide covers deploying Abbas FIT on cPanel (Backend + Web) and building the mobile app using VS Code or Android Studio.

---

## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Part A: cPanel Deployment (Backend + Web)](#part-a-cpanel-deployment)
3. [Part B: Mobile App Deployment](#part-b-mobile-app-deployment)
4. [Part C: Environment Configuration](#part-c-environment-configuration)
5. [Troubleshooting](#troubleshooting)

---

## Prerequisites

### Required Accounts & Tools
- [ ] cPanel hosting account with:
  - Python support (Python 3.9+)
  - Node.js support (Node 18+)
  - MongoDB database OR MongoDB Atlas account (free tier available)
  - SSL certificate (usually free with cPanel)
- [ ] Expo account (free): https://expo.dev/signup
- [ ] Google Play Developer account ($25 one-time): https://play.google.com/console
- [ ] Apple Developer account ($99/year): https://developer.apple.com (for iOS)

### Local Tools
- [ ] VS Code with extensions: Python, ESLint, Expo Tools
- [ ] Node.js 18+ installed
- [ ] Python 3.9+ installed
- [ ] Git installed
- [ ] Android Studio (for Android builds)
- [ ] Xcode (for iOS builds, Mac only)

---

## Part A: cPanel Deployment

### Step 1: Prepare Your Domain & SSL

1. **Login to cPanel** → Go to your hosting provider's cPanel
2. **Setup Domain**: 
   - Main domain: `yourdomain.com` (for landing page)
   - Subdomain: `api.yourdomain.com` (for backend API)
3. **Enable SSL**:
   - Go to **SSL/TLS Status** → Install free Let's Encrypt certificate
   - Enable for both main domain and api subdomain

### Step 2: Setup MongoDB Database

#### Option A: MongoDB Atlas (Recommended - Free Tier)
1. Go to https://www.mongodb.com/atlas
2. Create free account → Create new cluster (M0 Free tier)
3. **Database Access** → Add new user:
   - Username: `abbasfit_user`
   - Password: (generate strong password)
   - Role: `readWriteAnyDatabase`
4. **Network Access** → Add IP Address:
   - Click "Allow Access from Anywhere" (0.0.0.0/0) for cPanel
5. **Connect** → Get connection string:
   ```
   mongodb+srv://abbasfit_user:<password>@cluster0.xxxxx.mongodb.net/abbasfit?retryWrites=true&w=majority
   ```

#### Option B: cPanel MongoDB (if available)
1. Go to **Databases** → **MongoDB Databases**
2. Create database: `abbasfit`
3. Create user with full privileges
4. Note the connection string (usually `mongodb://localhost:27017/abbasfit`)

### Step 3: Deploy Backend (FastAPI)

#### 3.1 Upload Backend Files
1. **File Manager** → Navigate to your api subdomain folder (e.g., `/home/username/api.yourdomain.com/`)
2. Upload these files from `/app/backend/`:
   ```
   server.py
   requirements.txt
   .env (create new - see Step 3.3)
   ```

#### 3.2 Setup Python Application in cPanel
1. Go to **Setup Python App**
2. Click **Create Application**:
   - Python version: `3.9` or higher
   - Application root: `/home/username/api.yourdomain.com`
   - Application URL: `api.yourdomain.com`
   - Application startup file: `server.py`
   - Application Entry point: `app`
3. Click **Create**

#### 3.3 Create Backend .env File
Create `/home/username/api.yourdomain.com/.env`:
```env
# MongoDB Connection
MONGO_URL=mongodb+srv://abbasfit_user:YOUR_PASSWORD@cluster0.xxxxx.mongodb.net/abbasfit?retryWrites=true&w=majority

# JWT Secret (generate a random 32+ character string)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Optional: Gemini API Key (for AI features)
GEMINI_API_KEY=your-gemini-api-key

# CORS Origins (your frontend URLs)
CORS_ORIGINS=https://yourdomain.com,https://www.yourdomain.com
```

#### 3.4 Install Dependencies
1. In cPanel Python App, click **Enter to virtual environment**
2. Copy the command and run in **Terminal**:
   ```bash
   source /home/username/virtualenv/api.yourdomain.com/3.9/bin/activate
   cd /home/username/api.yourdomain.com
   pip install -r requirements.txt
   ```

#### 3.5 Configure WSGI (Important!)
Create `/home/username/api.yourdomain.com/passenger_wsgi.py`:
```python
import sys
import os

# Add the app directory to the path
sys.path.insert(0, os.path.dirname(__file__))

# Load environment variables
from dotenv import load_dotenv
load_dotenv()

# Import the FastAPI app
from server import app

# For Passenger WSGI
application = app
```

#### 3.6 Restart Application
1. Go back to **Setup Python App**
2. Click **Restart** on your application

#### 3.7 Test Backend
Visit `https://api.yourdomain.com/api/health` - should return:
```json
{"status": "healthy", "timestamp": "..."}
```

### Step 4: Deploy Frontend (Web Version)

#### 4.1 Build Web Version Locally
On your local machine:
```bash
cd /app/frontend

# Update .env for production
echo "EXPO_PUBLIC_BACKEND_URL=https://api.yourdomain.com" > .env.production

# Install dependencies
npm install

# Build for web
npx expo export --platform web
```

This creates a `dist/` folder with static files.

#### 4.2 Upload to cPanel
1. **File Manager** → Navigate to `/home/username/public_html/` (or your domain folder)
2. **Delete** existing files (backup first if needed)
3. **Upload** all contents from `dist/` folder
4. Ensure `index.html` is in the root

#### 4.3 Configure .htaccess for Single Page App
Create `/home/username/public_html/.htaccess`:
```apache
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  
  # Handle React Router / Expo Router
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !^/api
  RewriteRule ^ index.html [QSA,L]
  
  # Proxy API requests to backend (if same domain)
  # RewriteRule ^api/(.*)$ https://api.yourdomain.com/api/$1 [P,L]
</IfModule>

# Enable compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json
</IfModule>

# Cache static assets
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType application/javascript "access plus 1 week"
</IfModule>
```

#### 4.4 Test Web App
Visit `https://yourdomain.com` - should show the Abbas FIT landing page.

---

## Part B: Mobile App Deployment

### Option 1: Using VS Code + Expo (Easiest)

#### Step 1: Install EAS CLI
```bash
npm install -g eas-cli
eas login  # Login with your Expo account
```

#### Step 2: Configure for Production
Update `/app/frontend/app.json`:
```json
{
  "expo": {
    "name": "Abbas FIT",
    "slug": "abbasfit",
    "version": "1.0.0",
    "extra": {
      "EXPO_PUBLIC_BACKEND_URL": "https://api.yourdomain.com",
      "eas": {
        "projectId": "your-expo-project-id"
      }
    },
    "android": {
      "package": "com.abbasfit.app",
      "versionCode": 1
    },
    "ios": {
      "bundleIdentifier": "com.abbasfit.app",
      "buildNumber": "1.0.0"
    }
  }
}
```

#### Step 3: Create eas.json
Create `/app/frontend/eas.json`:
```json
{
  "cli": {
    "version": ">= 5.0.0"
  },
  "build": {
    "development": {
      "developmentClient": true,
      "distribution": "internal"
    },
    "preview": {
      "distribution": "internal",
      "android": {
        "buildType": "apk"
      }
    },
    "production": {
      "android": {
        "buildType": "app-bundle"
      },
      "ios": {
        "resourceClass": "m-medium"
      }
    }
  },
  "submit": {
    "production": {
      "android": {
        "serviceAccountKeyPath": "./google-service-account.json",
        "track": "production"
      },
      "ios": {
        "appleId": "your-apple-id@email.com",
        "ascAppId": "your-app-store-connect-app-id"
      }
    }
  }
}
```

#### Step 4: Build Android APK (for testing)
```bash
cd /app/frontend
eas build --platform android --profile preview
```
This builds an APK you can install directly on Android devices.

#### Step 5: Build Android App Bundle (for Play Store)
```bash
eas build --platform android --profile production
```

#### Step 6: Build iOS (requires Mac or EAS)
```bash
eas build --platform ios --profile production
```

#### Step 7: Submit to Stores
```bash
# Android - Submit to Google Play
eas submit --platform android --profile production

# iOS - Submit to App Store
eas submit --platform ios --profile production
```

### Option 2: Using Android Studio (Manual Build)

#### Step 1: Generate Native Project
```bash
cd /app/frontend
npx expo prebuild --platform android
```
This creates an `android/` folder.

#### Step 2: Open in Android Studio
1. Open Android Studio
2. File → Open → Select `/app/frontend/android`
3. Wait for Gradle sync to complete

#### Step 3: Configure Signing
1. Build → Generate Signed Bundle / APK
2. Create new keystore:
   - Key store path: `my-release-key.keystore`
   - Password: (create secure password)
   - Alias: `abbasfit`
   - Validity: 10000 days
3. Save keystore file securely (you'll need it for updates!)

#### Step 4: Update gradle.properties
Add to `/app/frontend/android/gradle.properties`:
```properties
MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=abbasfit
MYAPP_RELEASE_STORE_PASSWORD=your-store-password
MYAPP_RELEASE_KEY_PASSWORD=your-key-password
```

#### Step 5: Build Release APK/AAB
1. Build → Generate Signed Bundle / APK
2. Select **Android App Bundle** (for Play Store) or **APK** (for direct install)
3. Select **release** build variant
4. Click **Create**

Output location: `android/app/build/outputs/bundle/release/app-release.aab`

#### Step 6: Upload to Google Play Console
1. Go to https://play.google.com/console
2. Create new application
3. Fill in store listing (title, description, screenshots)
4. Upload your AAB file to Production track
5. Complete content rating questionnaire
6. Set up pricing (free/paid)
7. Submit for review

---

## Part C: Environment Configuration

### Production Environment Variables

#### Backend (.env)
```env
# Required
MONGO_URL=mongodb+srv://user:pass@cluster.mongodb.net/abbasfit
JWT_SECRET=generate-a-64-character-random-string-here

# Optional
GEMINI_API_KEY=your-gemini-api-key
CORS_ORIGINS=https://yourdomain.com,https://www.yourdomain.com

# Email notifications (optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
```

#### Frontend (app.json extra)
```json
{
  "extra": {
    "EXPO_PUBLIC_BACKEND_URL": "https://api.yourdomain.com"
  }
}
```

### Generate Secure JWT Secret
```bash
# Run this in terminal
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

---

## Troubleshooting

### Backend Issues

#### "502 Bad Gateway" on cPanel
- Check Python app is running in cPanel
- Verify `passenger_wsgi.py` exists and is correct
- Check error logs: cPanel → Errors

#### "MongoDB connection failed"
- Verify MongoDB Atlas IP whitelist includes `0.0.0.0/0`
- Check connection string format
- Test connection: `mongosh "your-connection-string"`

#### CORS Errors
- Add your domain to `CORS_ORIGINS` in backend .env
- Restart Python app after changes

### Frontend Issues

#### "Network request failed" on mobile
- Ensure backend URL uses HTTPS
- Check SSL certificate is valid
- Verify API is accessible: `curl https://api.yourdomain.com/api/health`

#### Build fails on EAS
- Run `eas build --clear-cache`
- Check `app.json` for syntax errors
- Ensure all required fields are present

### Mobile App Issues

#### App crashes on startup
- Check backend URL is correct in app.json
- Verify API is accessible from mobile network
- Check Expo logs: `eas build:view`

#### Google Play rejection
- Ensure privacy policy is accessible
- Add required permissions explanations
- Complete all store listing requirements

---

## Quick Commands Reference

```bash
# Backend - Test locally
cd /app/backend
pip install -r requirements.txt
uvicorn server:app --reload --host 0.0.0.0 --port 8001

# Frontend - Test locally
cd /app/frontend
npm install
npx expo start

# Build web
npx expo export --platform web

# Build Android APK (testing)
eas build --platform android --profile preview

# Build Android AAB (production)
eas build --platform android --profile production

# Build iOS
eas build --platform ios --profile production

# Submit to stores
eas submit --platform android
eas submit --platform ios
```

---

## Support

For issues with:
- **Expo/EAS**: https://docs.expo.dev
- **cPanel**: Contact your hosting provider
- **MongoDB Atlas**: https://docs.atlas.mongodb.com
- **Google Play**: https://support.google.com/googleplay/android-developer
- **App Store**: https://developer.apple.com/support

---

**Last Updated**: January 2025
**App Version**: 2.0.0
