# Abbas FIT - Deployment Guide

This guide will help you deploy Abbas FIT on your own hosting with **both website and mobile app** access.

## Architecture Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                     YOUR HOSTING SERVER                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ┌─────────────────┐    ┌─────────────────────────────────┐   │
│   │   MongoDB       │    │     FastAPI Backend             │   │
│   │   Database      │◄──►│     (api.yourdomain.com)        │   │
│   │   Port: 27017   │    │     Port: 8001                  │   │
│   └─────────────────┘    └───────────────┬─────────────────┘   │
│                                          │                      │
│                          ┌───────────────┴───────────────┐     │
│                          │                               │     │
│   ┌──────────────────────▼────┐    ┌─────────────────────▼──┐  │
│   │      WEB VERSION          │    │     MOBILE APP         │  │
│   │   (yourdomain.com)        │    │   (Android/iOS APK)    │  │
│   │   Static HTML/JS/CSS      │    │   Built with Expo      │  │
│   └───────────────────────────┘    └────────────────────────┘  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Users can access via:
✅ Website: https://yourdomain.com
✅ Mobile App: Android APK / iOS App
✅ Admin Panel: Same website/app with admin login
```

## Prerequisites

- Python 3.11+ (for backend)
- MongoDB 6.0+ (database)
- Node.js 18+ (for building web & mobile)
- Docker & Docker Compose (optional, recommended)

## Project Structure

```
abbasfit/
├── backend/           # FastAPI backend
│   ├── server.py      # Main application
│   ├── config.py      # Configuration
│   ├── requirements.txt
│   ├── Dockerfile
│   └── .env.example
├── frontend/          # Expo React Native app
│   ├── app/           # Screens
│   ├── src/           # Components, services
│   └── app.json
├── docker-compose.yml # Docker setup
└── DEPLOYMENT.md      # This file
```

---

## Option 1: Docker Deployment (Recommended)

### Step 1: Clone and Configure

```bash
# Clone your repository
git clone https://github.com/yourusername/abbasfit.git
cd abbasfit

# Create environment file
cp backend/.env.example backend/.env
```

### Step 2: Edit Environment Variables

Edit `backend/.env`:

```env
MONGO_URL="mongodb://mongodb:27017"
DB_NAME="abbasfit_db"
JWT_SECRET_KEY="your-super-secret-key-minimum-32-characters"
EMERGENT_LLM_KEY="your-api-key-for-ai-features"
```

### Step 3: Start Services

```bash
# Build and start all services
docker-compose up -d --build

# Check status
docker-compose ps

# View logs
docker-compose logs -f backend
```

### Step 4: Verify Installation

```bash
# Health check
curl http://localhost:8001/api/health

# Test login
curl -X POST http://localhost:8001/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "admin@abbasfit.com", "password": "admin"}'
```

---

## Option 2: Manual Deployment

### Step 1: Setup MongoDB

**Option A: Local MongoDB**
```bash
# Ubuntu/Debian
sudo apt install mongodb
sudo systemctl start mongodb
```

**Option B: MongoDB Atlas (Cloud)**
1. Create account at https://www.mongodb.com/atlas
2. Create a free cluster
3. Get connection string: `mongodb+srv://user:pass@cluster.mongodb.net/abbasfit_db`

### Step 2: Setup Backend

```bash
cd backend

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Linux/Mac
# or: venv\Scripts\activate  # Windows

# Install dependencies
pip install -r requirements.txt

# Create .env file
cp .env.example .env
# Edit .env with your settings

# Run the server
uvicorn server:app --host 0.0.0.0 --port 8001
```

### Step 3: Setup with Supervisor (Production)

Create `/etc/supervisor/conf.d/abbasfit.conf`:

```ini
[program:abbasfit]
command=/path/to/venv/bin/uvicorn server:app --host 0.0.0.0 --port 8001
directory=/path/to/abbasfit/backend
user=www-data
autostart=true
autorestart=true
stderr_logfile=/var/log/abbasfit/error.log
stdout_logfile=/var/log/abbasfit/access.log
```

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start abbasfit
```

### Step 4: Nginx Reverse Proxy (Optional)

Create `/etc/nginx/sites-available/abbasfit`:

```nginx
server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        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;
    }
}
```

```bash
sudo ln -s /etc/nginx/sites-available/abbasfit /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

---

## Web Version Deployment (Website)

The Abbas FIT app can be accessed via web browser - same codebase as mobile!

### Step 1: Update API URL

Edit `frontend/.env.production`:

```env
EXPO_PUBLIC_BACKEND_URL=https://api.yourdomain.com
```

### Step 2: Build Web Version

```bash
cd frontend

# Install dependencies
npm install
# or: yarn install

# Build for web (creates /dist folder)
npx expo export --platform web

# The output will be in /dist folder
```

### Step 3: Deploy Web Files

The `/dist` folder contains static files (HTML, JS, CSS). Deploy them to:

**Option A: Same Server as API (Nginx)**

```nginx
# /etc/nginx/sites-available/abbasfit-web
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/abbasfit/dist;
    index index.html;

    # Handle SPA routing
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Cache static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
```

**Option B: Shared Hosting (cPanel/Plesk)**

1. Upload contents of `/dist` folder to `public_html`
2. Create `.htaccess` file for SPA routing:

```apache
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>
```

**Option C: Vercel/Netlify (Free)**

```bash
# Vercel
npx vercel --prod

# Netlify
npx netlify deploy --prod --dir=dist
```

### Step 4: Configure CORS

Make sure your backend allows your web domain. Update `backend/.env`:

```env
ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com
```

---

## Mobile App Configuration

### Update API URL

Edit `frontend/.env.production`:

# Build APK
npx expo build:android -t apk

# Or use EAS Build (recommended)
npx eas build --platform android --profile production
```

### Build for iOS

```bash
npx eas build --platform ios --profile production
```

---

## Environment Variables Reference

| Variable | Description | Required | Default |
|----------|-------------|----------|---------||
| `MONGO_URL` | MongoDB connection string | Yes | `mongodb://localhost:27017` |
| `DB_NAME` | Database name | Yes | `abbasfit_db` |
| `JWT_SECRET_KEY` | Secret for JWT tokens | Yes | - |
| `EMERGENT_LLM_KEY` | API key for AI features | No | - |
| `HOST` | Server host | No | `0.0.0.0` |
| `PORT` | Server port | No | `8001` |
| `ALLOWED_ORIGINS` | CORS origins (comma-separated) | No | `*` |

---

## Default Admin Credentials

**Email:** `admin@abbasfit.com`  
**Password:** `admin`

⚠️ **IMPORTANT:** Change the admin password after first login!

---

## API Endpoints Reference

### Public
- `GET /api/health` - Health check
- `GET /api/testimonials` - Get testimonials
- `POST /api/contact` - Submit contact form

### Authentication
- `POST /api/auth/login` - Login
- `GET /api/auth/me` - Get current user

### Admin (requires admin token)
- `GET /api/admin/users` - List users
- `POST /api/admin/users` - Create user
- `PUT /api/admin/users/{id}` - Update user
- `DELETE /api/admin/users/{id}` - Delete user
- `GET /api/admin/insights` - Dashboard insights
- `GET /api/admin/contacts` - View contact submissions

### User (requires user token)
- `GET /api/user/dashboard-stats` - Dashboard data
- `POST /api/user/vitals` - Log vitals
- `GET /api/user/vitals` - Get vitals history
- `POST /api/user/meals` - Log meal
- `GET /api/user/meals` - Get meals
- `POST /api/user/activities` - Log activity
- `GET /api/user/activities` - Get activities

### AI Features
- `POST /api/ai/analyze-meal` - Analyze meal with AI
- `POST /api/ai/predict-goals` - Get AI goal predictions

---

## Troubleshooting

### MongoDB Connection Issues
```bash
# Check if MongoDB is running
sudo systemctl status mongodb

# Check connection
mongosh mongodb://localhost:27017
```

### Backend Not Starting
```bash
# Check logs
tail -f /var/log/abbasfit/error.log

# Test manually
cd backend && python -c "from server import app; print('OK')"
```

### CORS Errors
Update `ALLOWED_ORIGINS` in your `.env` file to include your frontend domain.

---

## Security Checklist

- [ ] Change default admin password
- [ ] Set strong JWT_SECRET_KEY (min 32 characters)
- [ ] Enable HTTPS with SSL certificate
- [ ] Configure firewall (allow only ports 80, 443)
- [ ] Set up regular database backups
- [ ] Update ALLOWED_ORIGINS for production
- [ ] Keep dependencies updated

---

## Support

For issues or questions, please create an issue in your GitHub repository.
