# DrJobs - Employer Job Service API

Complete setup guide for deploying the DrJobs Employer Job Service on a server.

---

## 📋 Table of Contents

- [System Requirements](#system-requirements)
- [Server Prerequisites](#server-prerequisites)
- [Installation Steps](#installation-steps)
- [Configuration](#configuration)
- [Database Setup](#database-setup)
- [Running the Application](#running-the-application)
- [Troubleshooting](#troubleshooting)
- [API Documentation](#api-documentation)

---

## 🖥️ System Requirements

### Required Software Versions

| Software | Version | Notes |
|----------|---------|-------|
| **PHP** | `^8.2` | PHP 8.2 or higher required |
| **Composer** | `^2.0` | Latest version recommended |
| **MongoDB** | `^6.0` | MongoDB 6.0 or higher |
| **Node.js** | `^18.0` | For frontend assets |
| **NPM** | `^9.0` | Package manager |
| **Web Server** | Apache/Nginx | With PHP-FPM |

### Required PHP Extensions

```bash
- php-mongodb (MongoDB driver)
- php-mbstring
- php-xml
- php-curl
- php-zip
- php-bcmath
- php-json
- php-openssl
- php-tokenizer
- php-fileinfo
- php-pdo
- php-redis (optional, for caching)
```

---

## 🔧 Server Prerequisites

### 1. Install PHP 8.2

**Ubuntu/Debian:**
```bash
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install -y php8.2 php8.2-cli php8.2-fpm php8.2-mbstring \
    php8.2-xml php8.2-curl php8.2-zip php8.2-bcmath php8.2-redis
```

**Verify installation:**
```bash
php -v
# Should show: PHP 8.2.x
```

### 2. Install MongoDB PHP Extension

```bash
sudo pecl install mongodb
echo "extension=mongodb.so" | sudo tee /etc/php/8.2/mods-available/mongodb.ini
sudo phpenmod mongodb
sudo systemctl restart php8.2-fpm
```

**Verify MongoDB extension:**
```bash
php -m | grep mongodb
# Should output: mongodb
```

### 3. Install Composer

```bash
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer
composer --version
```

### 4. Install Node.js & NPM

```bash
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
node --version
npm --version
```

### 5. Install MongoDB Server

```bash
# Import MongoDB public key
curl -fsSL https://www.mongodb.org/static/pgp/server-6.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.gpg

# Add MongoDB repository
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

# Install MongoDB
sudo apt update
sudo apt install -y mongodb-org

# Start MongoDB service
sudo systemctl start mongod
sudo systemctl enable mongod

# Verify MongoDB is running
sudo systemctl status mongod
```

---

## 📥 Installation Steps

### Step 1: Clone Repository

```bash
cd /var/www/html
git clone <repository-url> drjobs
cd drjobs
```

### Step 2: Set Correct Permissions

```bash
sudo chown -R www-data:www-data /var/www/html/drjobs
sudo chmod -R 755 /var/www/html/drjobs
sudo chmod -R 775 /var/www/html/drjobs/storage
sudo chmod -R 775 /var/www/html/drjobs/bootstrap/cache
```

### Step 3: Install PHP Dependencies

```bash
composer install --no-dev --optimize-autoloader
```

**For development environment:**
```bash
composer install
```

### Step 4: Install Node Dependencies

```bash
npm install
npm run build
```

### Step 5: Environment Configuration

```bash
cp .env.example .env
php artisan key:generate
```

---

## ⚙️ Configuration

### 1. Edit `.env` File

```bash
nano .env
```

Copy the following template and fill in your actual values:

```dotenv
# Application Configuration
APP_NAME=
APP_ENV=
APP_KEY=
APP_DEBUG=
APP_URL=
THIRD_PARTY_JOBS_URL=

# Application Timezone
APP_TIMEZONE=

# Localization
APP_LOCALE=
APP_FALLBACK_LOCALE=
APP_FAKER_LOCALE=

# Maintenance
APP_MAINTENANCE_DRIVER=

# Security
BCRYPT_ROUNDS=

# Logging
LOG_CHANNEL=
LOG_STACK=
LOG_DEPRECATIONS_CHANNEL=
LOG_LEVEL=

# Default Database Connection
DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
DB_AUTHENTICATION_DATABASE=

# Secondary/Employer Database Connection
DB_EMPLOYER_HOST=
DB_EMPLOYER_PORT=
DB_EMPLOYER_DATABASE=
DB_EMPLOYER_USERNAME=
DB_EMPLOYER_PASSWORD=
DB_EMPLOYER_AUTH_DATABASE=

# Session Configuration
SESSION_DRIVER=
SESSION_LIFETIME=
SESSION_ENCRYPT=
SESSION_PATH=
SESSION_DOMAIN=

# Broadcasting
BROADCAST_CONNECTION=

# Filesystem
FILESYSTEM_DISK=

# Queue
QUEUE_CONNECTION=

# Cache
CACHE_STORE=

# Memcached
MEMCACHED_HOST=

# Redis Configuration
REDIS_CLIENT=
REDIS_HOST=
REDIS_PASSWORD=
REDIS_PORT=

# Mail Configuration
MAIL_MAILER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=

# AWS S3 Configuration
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=
AWS_BUCKET=
AWS_URL=

# Vite
VITE_APP_NAME=

# API Configuration
API_PREFIX=
API_VERSION=

# JWT Configuration
JWT_SECRET=
JWT_TTL=

# OpenAI Configuration
OPENAI_API_KEY=
OPEN_AI_MODEL=

# Third Party API
THIRD_PARTY_JOBSEEKER_API_URL=
THIRD_PARTY_API_URL=
THIRD_PARTY_API_AUTH_USER_NAME=
THIRD_PARTY_API_AUTH_PASSWORD=

# AI API
AI_API_URL=

# PayPal Configuration
PAYPAL_CLIENT_ID=
PAYPAL_CLIENT_SECRET=
PAYPAL_WEBHOOK_ID=
PAYPAL_MODE=

# Telr Payment Gateway
TELR_STORE_ID=
TELR_AUTH_KEY=
TELR_MODE=
TELR_REMOTE_AUTH_KEY=

# Matching & Screening Percentages
POTENTIAL_MATCHING_PERCENTAGE=
VERIFY_MATCHING_PERCENTAGE=
SCREENING_MATCHING_PERCENTAGE=
PROFILE_SCORE_PERCENTAGE=

# Agora Video SDK Credentials
AGORA_APP_ID=
AGORA_APP_CERTIFICATE=

# Agora Cloud Recording Credentials
AGORA_CUSTOMER_ID=
AGORA_CUSTOMER_SECRET=

# Agora Cloud Recording Storage
AGORA_STORAGE_VENDOR=
AGORA_STORAGE_REGION=

# Currency Conversion
AED_CONVERTION_RATE=

# Subscription Period Configuration (in days)
SUBSCRIPTION_MONTHLY_DAYS=
SUBSCRIPTION_YEARLY_DAYS=
```

### 2. Configure Queue Worker (Optional)

For background job processing:

```bash
sudo nano /etc/supervisor/conf.d/drjobs-worker.conf
```

Add:
```ini
[program:drjobs-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/drjobs/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/html/drjobs/storage/logs/worker.log
stopwaitsecs=3600
```

Reload supervisor:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start drjobs-worker:*
```

---

## 🗄️ Database Setup

### 1. Create MongoDB Database & User

```bash
mongosh
```

In MongoDB shell:
```javascript
use drjobs

// Create database user
db.createUser({
  user: "drjobs_user",
  pwd: "your_secure_password",
  roles: [
    { role: "readWrite", db: "drjobs" }
  ]
})

// Verify user creation
db.getUsers()

exit
```

### 2. Run Database Seeders

**Seed Email Templates:**
```bash
php artisan db:seed --class=EmailTemplateSeeder
```

**Seed All Data:**
```bash
php artisan db:seed
```

### 3. Create Indexes (Optional - for performance)

```bash
php artisan tinker
```

In Tinker:
```php
DB::connection('mongodb')->getCollection('email_templates')->createIndex(['key' => 1], ['unique' => true]);
DB::connection('mongodb')->getCollection('email_templates')->createIndex(['status' => 1]);
exit
```

---

## 🚀 Running the Application

### Web Server Configuration

#### Apache Configuration

Create virtual host:
```bash
sudo nano /etc/apache2/sites-available/drjobs.conf
```

Add:
```apache
<VirtualHost *:80>
    ServerName api.drjobs.com
    ServerAlias www.api.drjobs.com
    DocumentRoot /var/www/html/drjobs/public

    <Directory /var/www/html/drjobs/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/drjobs-error.log
    CustomLog ${APACHE_LOG_DIR}/drjobs-access.log combined
</VirtualHost>
```

Enable site and rewrite module:
```bash
sudo a2enmod rewrite
sudo a2ensite drjobs.conf
sudo systemctl restart apache2
```

#### Nginx Configuration

```bash
sudo nano /etc/nginx/sites-available/drjobs
```

Add:
```nginx
server {
    listen 80;
    server_name api.drjobs.com;
    root /var/www/html/drjobs/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

Enable site:
```bash
sudo ln -s /etc/nginx/sites-available/drjobs /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### SSL Certificate (Production)

Install Certbot:
```bash
sudo apt install certbot python3-certbot-nginx
```

Generate certificate:
```bash
sudo certbot --nginx -d api.drjobs.com -d www.api.drjobs.com
```

### Optimize for Production

```bash
# Cache configuration
php artisan config:cache

# Cache routes
php artisan route:cache

# Cache views
php artisan view:cache

# Optimize autoloader
composer dump-autoload --optimize
```

---

## 🔍 Troubleshooting

### Common Issues

**1. MongoDB Connection Error**

```bash
# Check if MongoDB is running
sudo systemctl status mongod

# Check MongoDB logs
sudo tail -f /var/log/mongodb/mongod.log

# Test MongoDB connection
mongosh --host 127.0.0.1 --port 27017
```

**2. Permission Errors**

```bash
# Fix storage permissions
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache
```

**3. Composer Memory Limit**

```bash
# Increase memory limit for composer
COMPOSER_MEMORY_LIMIT=-1 composer install
```

**4. PHP Extensions Missing**

```bash
# Check installed extensions
php -m

# Install missing extension (example)
sudo apt install php8.2-mongodb
sudo systemctl restart php8.2-fpm
```

**5. Clear All Caches**

```bash
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
composer dump-autoload
```

### Logs Location

- **Laravel Logs:** `/var/www/html/drjobs/storage/logs/laravel.log`
- **Apache Logs:** `/var/log/apache2/drjobs-*.log`
- **Nginx Logs:** `/var/log/nginx/access.log` & `/var/log/nginx/error.log`
- **PHP-FPM Logs:** `/var/log/php8.2-fpm.log`
- **MongoDB Logs:** `/var/log/mongodb/mongod.log`

---

## 📚 API Documentation

### Available Documentation Files

- **Admin API:** See `ADMIN_API_DOCUMENTATION.md`
- **Agora Recording API:** See `AGORA_RECORDING_API.md`
- **API Routes:** See `routes/api.php`

### API Base URL

```
Production: https://api.drjobs.com/api
Development: http://localhost:8000/api
```

### Key API Endpoints

- **Authentication:** `/api/login`, `/api/register`
- **Email Templates:** `/api/admin/email-templates` (Admin only)
- **Jobs:** `/api/employer-job/*`
- **Interviews:** `/api/interview/*`
- **Subscription Plans:** `/api/subscription-plans/*`

### Admin Panel Access

- **Endpoint:** `/api/admin/login`
- **Protected Routes:** Use `auth.admin` middleware

---

## 🔒 Security Best Practices

1. **Never commit `.env` file to version control**
2. **Use strong passwords for database users**
3. **Keep `APP_DEBUG=false` in production**
4. **Enable HTTPS with valid SSL certificates**
5. **Regularly update dependencies:**
   ```bash
   composer update
   npm update
   ```
6. **Set up firewall rules:**
   ```bash
   sudo ufw allow 80/tcp
   sudo ufw allow 443/tcp
   sudo ufw allow 27017/tcp  # MongoDB (restrict to localhost only)
   sudo ufw enable
   ```
7. **Regular backups of MongoDB database**

---

## 📞 Support

For technical issues or questions, contact the development team.

---

## 📝 License

This project is proprietary software. All rights reserved.

---

**Last Updated:** January 2026  
**Version:** 1.0.0
