# Deployment Guide for aibitadmin.aibitsoft.cloud

This guide ensures safe deployment without affecting other projects in the shared hosting environment.

## Prerequisites

- Node.js installed (check with `node -v` and `npm -v`)
- PM2 installed globally: `npm install -g pm2`
- MongoDB Atlas account (or MongoDB connection string)
- All environment variables configured

## Step 1: Verify Project Isolation

This project is deployed in its own directory:
```
/home/aibitsofts/public_html/aibitadmin.aibitsoft.cloud/
```

**Important:** This directory is isolated from other projects:
- `admin-dashboard.aibitsoft.cloud`
- `backend.aibitsoft.cloud`
- `barber.aibitsoft.cloud`
- `chatbot.aibitsoft.cloud`
- `hr.aibitsoft.cloud`
- `marketplace.aibitsoft.cloud`
- etc.

Each project runs independently with its own:
- Node.js process (different PM2 app name)
- Port (if needed)
- Environment variables
- Dependencies

## Step 2: Navigate to Project Directory

```bash
cd /home/aibitsofts/public_html/aibitadmin.aibitsoft.cloud
```

## Step 3: Install Dependencies

```bash
npm install --production
```

**Note:** If you need dev dependencies (like nodemon), use:
```bash
npm install
```

## Step 4: Configure Environment Variables

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

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

**Required variables:**
- `PORT` - Port number (default: 4000)
- `NODE_ENV` - Set to `production`
- `MONGO_URL` or `MONGODB_URI` - Your MongoDB connection string
- `JWT_SECRET` - A strong random secret for JWT tokens
- `CLOUDINARY_*` - Cloudinary credentials (if using file uploads)
- `SMTP_*` - Email configuration (if sending emails)
- `ZOOM_*` - Zoom credentials (if using Zoom integration)

3. Save and exit the editor.

## Step 5: Build the Application

```bash
npm run build
```

This will:
- Clean the `dist/` directory
- Copy all source files from `src/` to `dist/`
- Prepare the application for production

## Step 6: Create Logs Directory

```bash
mkdir -p logs
```

PM2 will write logs here (configured in `ecosystem.config.js`).

## Step 7: Start with PM2

### Option A: Using Ecosystem File (Recommended)

```bash
pm2 start ecosystem.config.js
```

### Option B: Manual Start

```bash
pm2 start dist/server.js --name "aibitadmin-backend" --env production
```

## Step 8: Save PM2 Configuration

```bash
# Save current PM2 process list
pm2 save

# Setup PM2 to start on server reboot (if you have sudo access)
pm2 startup
# Follow the instructions shown
```

## Step 9: Verify Deployment

```bash
# Check PM2 status
pm2 status

# View logs
pm2 logs aibitadmin-backend

# Check if the app is responding
curl http://localhost:4000/api/health
```

Expected response:
```json
{
  "status": "ok",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "environment": "production"
}
```

## Step 10: Configure Web Server (cPanel/Node.js Selector)

Since this is cPanel shared hosting, you'll need to configure the Node.js Selector in cPanel:

1. Log into cPanel
2. Find "Node.js Selector" or "Setup Node.js App"
3. Create a new Node.js application:
   - **Application root:** `/home/aibitsofts/public_html/aibitadmin.aibitsoft.cloud`
   - **Application URL:** `aibitadmin.aibitsoft.cloud`
   - **Application startup file:** `dist/server.js`
   - **Application port:** `4000` (or your configured PORT)
   - **Node.js version:** Latest LTS (18.x or 20.x)

4. The cPanel Node.js Selector will handle:
   - Process management (may override PM2)
   - Reverse proxy setup
   - SSL certificate (if available)

**Alternative:** If cPanel doesn't have Node.js Selector, you may need to:
- Use PM2 (as configured above)
- Configure Apache/Nginx reverse proxy manually
- Or use a `.htaccess` file (see below)

## Step 11: Update .htaccess (If Needed)

The current `.htaccess` is configured for PHP. For Node.js apps on Apache with mod_proxy, you might need:

```apache
# Allow AutoSSL/ACME HTTP DCV - serve .well-known from disk
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^\.?well-known/ - [L]

# Proxy to Node.js app (if Apache mod_proxy is enabled)
RewriteCond %{REQUEST_URI} ^/api/
RewriteRule ^(.*)$ http://localhost:4000/$1 [P,L]
</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# Set the "ea-php82" package as the default "PHP" programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php82 .php .php8 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
```

**Note:** Only add the proxy rules if Apache `mod_proxy` and `mod_proxy_http` are enabled. Otherwise, rely on cPanel's Node.js Selector or PM2.

## Step 12: Verify External Access

Once configured, test from outside:

```bash
curl https://aibitadmin.aibitsoft.cloud/api/health
```

## Useful PM2 Commands

```bash
# View status
pm2 status

# View logs (last 100 lines)
pm2 logs aibitadmin-backend --lines 100

# Restart application
pm2 restart aibitadmin-backend

# Stop application
pm2 stop aibitadmin-backend

# Delete application from PM2
pm2 delete aibitadmin-backend

# Monitor (real-time)
pm2 monit

# Reload (zero-downtime restart)
pm2 reload aibitadmin-backend
```

## Troubleshooting

### App not starting

1. Check PM2 logs:
   ```bash
   pm2 logs aibitadmin-backend --err
   ```

2. Check if port is already in use:
   ```bash
   netstat -tulpn | grep 4000
   # or
   lsof -i :4000
   ```

3. Verify environment variables:
   ```bash
   pm2 env aibitadmin-backend
   ```

### Database connection issues

1. Verify MongoDB connection string in `.env`
2. Check MongoDB Atlas IP whitelist (if using Atlas)
3. Test connection:
   ```bash
   node -e "require('dotenv').config(); const mongoose = require('mongoose'); mongoose.connect(process.env.MONGO_URL).then(() => console.log('Connected')).catch(e => console.error(e));"
   ```

### CORS errors

1. Verify the frontend domain is in `allowedOrigins` in `src/config/index.js`
2. Check browser console for the exact origin being blocked
3. Restart the application after config changes:
   ```bash
   pm2 restart aibitadmin-backend
   ```

### Port conflicts

If port 4000 is already in use by another project:

1. Change PORT in `.env`:
   ```env
   PORT=4001
   ```

2. Update `ecosystem.config.js`:
   ```js
   env: {
     NODE_ENV: "production",
     PORT: 4001,
   }
   ```

3. Restart:
   ```bash
   pm2 restart aibitadmin-backend
   ```

## Project Isolation Checklist

✅ **Isolated directory:** `/home/aibitsofts/public_html/aibitadmin.aibitsoft.cloud/`  
✅ **Unique PM2 app name:** `aibitadmin-backend`  
✅ **Unique port:** Configured via `.env` (default: 4000)  
✅ **Separate dependencies:** `node_modules/` in project directory  
✅ **Separate environment:** `.env` file in project directory  
✅ **Separate logs:** `logs/` directory in project directory  

## Updating the Application

When you need to update the code:

```bash
cd /home/aibitsofts/public_html/aibitadmin.aibitsoft.cloud

# Pull latest code (if using git)
git pull

# Or upload new files via FTP/cPanel File Manager

# Install any new dependencies
npm install --production

# Rebuild
npm run build

# Restart with PM2
pm2 restart aibitadmin-backend

# Or reload (zero-downtime)
pm2 reload aibitadmin-backend
```

## Security Notes

1. **Never commit `.env` file** - It's in `.gitignore`
2. **Use strong JWT_SECRET** - Generate with: `openssl rand -base64 32`
3. **Keep dependencies updated** - Run `npm audit` regularly
4. **Restrict MongoDB access** - Use IP whitelist in MongoDB Atlas
5. **Use HTTPS** - Configure SSL certificate in cPanel

## Support

If you encounter issues:
1. Check PM2 logs: `pm2 logs aibitadmin-backend`
2. Check application logs in `logs/` directory
3. Verify environment variables are set correctly
4. Test database connectivity
5. Verify port availability
