# Deployment Guide

## Overview

This guide covers deploying Qaya HRM to production environments, including server setup, configuration, optimization, and maintenance procedures.

---

## Prerequisites

### Server Requirements

**Minimum Requirements**:
- **CPU**: 2 cores
- **RAM**: 4 GB
- **Storage**: 20 GB SSD
- **Bandwidth**: 100 Mbps

**Recommended for Production**:
- **CPU**: 4+ cores
- **RAM**: 8+ GB
- **Storage**: 50+ GB SSD
- **Bandwidth**: 1 Gbps

### Software Requirements

- **Operating System**: Ubuntu 22.04 LTS (recommended) or CentOS 8+
- **Web Server**: Nginx 1.18+ or Apache 2.4+
- **PHP**: 8.2 or higher
- **Database**: MySQL 8.0+ or MariaDB 10.6+
- **Node.js**: 18.x or higher
- **Composer**: Latest version
- **Git**: For deployment
- **SSL Certificate**: Let's Encrypt or commercial

---

## Deployment Methods

### Method 1: Manual Deployment

#### Step 1: Server Setup

**Update System**:
```bash
sudo apt update
sudo apt upgrade -y
```

**Install Required Packages**:
```bash
# Install PHP and extensions
sudo apt install -y php8.2 php8.2-fpm php8.2-mysql php8.2-mbstring \
    php8.2-xml php8.2-bcmath php8.2-curl php8.2-zip php8.2-gd \
    php8.2-intl php8.2-redis

# Install Nginx
sudo apt install -y nginx

# Install MySQL
sudo apt install -y mysql-server

# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

# Install Git
sudo apt install -y git
```

#### Step 2: Database Setup

**Secure MySQL**:
```bash
sudo mysql_secure_installation
```

**Create Database and User**:
```bash
sudo mysql -u root -p
```

```sql
CREATE DATABASE qaya_hrm CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'qaya_user'@'localhost' IDENTIFIED BY 'strong_password_here';
GRANT ALL PRIVILEGES ON qaya_hrm.* TO 'qaya_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

#### Step 3: Application Deployment

**Clone Repository**:
```bash
cd /var/www
sudo git clone https://github.com/your-org/qaya-hrm.git
cd qaya-hrm
```

**Set Permissions**:
```bash
sudo chown -R www-data:www-data /var/www/qaya-hrm
sudo chmod -R 755 /var/www/qaya-hrm
sudo chmod -R 775 /var/www/qaya-hrm/storage
sudo chmod -R 775 /var/www/qaya-hrm/bootstrap/cache
```

**Install Dependencies**:
```bash
# PHP dependencies
composer install --optimize-autoloader --no-dev

# Node dependencies
npm install
npm run build
```

**Environment Configuration**:
```bash
cp .env.example .env
php artisan key:generate
```

**Edit .env file**:
```env
APP_NAME="Qaya HRM"
APP_ENV=production
APP_KEY=base64:...
APP_DEBUG=false
APP_URL=https://hrm.yourcompany.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=qaya_hrm
DB_USERNAME=qaya_user
DB_PASSWORD=strong_password_here

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@yourcompany.com
MAIL_FROM_NAME="${APP_NAME}"
```

**Run Migrations and Seeders**:
```bash
php artisan migrate --force
php artisan db:seed --force
```

**Create Storage Link**:
```bash
php artisan storage:link
```

**Optimize Application**:
```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
```

#### Step 4: Web Server Configuration

**Nginx Configuration**:

Create `/etc/nginx/sites-available/qaya-hrm`:
```nginx
server {
    listen 80;
    listen [::]:80;
    server_name hrm.yourcompany.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name hrm.yourcompany.com;
    root /var/www/qaya-hrm/public;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/hrm.yourcompany.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/hrm.yourcompany.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

    # Logging
    access_log /var/log/nginx/qaya-hrm-access.log;
    error_log /var/log/nginx/qaya-hrm-error.log;

    # Index
    index index.php;

    charset utf-8;

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

    # PHP-FPM
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    # Deny access to hidden files
    location ~ /\.(?!well-known).* {
        deny all;
    }

    # Client max body size
    client_max_body_size 20M;
}
```

**Enable Site**:
```bash
sudo ln -s /etc/nginx/sites-available/qaya-hrm /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

#### Step 5: SSL Certificate

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

**Obtain Certificate**:
```bash
sudo certbot --nginx -d hrm.yourcompany.com
```

**Auto-renewal**:
```bash
sudo certbot renew --dry-run
```

#### Step 6: Queue Worker Setup

**Create Supervisor Configuration**:

Create `/etc/supervisor/conf.d/qaya-hrm-worker.conf`:
```ini
[program:qaya-hrm-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/qaya-hrm/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/qaya-hrm/storage/logs/worker.log
stopwaitsecs=3600
```

**Start Supervisor**:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start qaya-hrm-worker:*
```

#### Step 7: Cron Job Setup

**Edit Crontab**:
```bash
sudo crontab -e -u www-data
```

**Add Laravel Scheduler**:
```cron
* * * * * cd /var/www/qaya-hrm && php artisan schedule:run >> /dev/null 2>&1
```

---

### Method 2: Docker Deployment

**Docker Compose Configuration**:

Create `docker-compose.yml`:
```yaml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: qaya-hrm-app
    restart: unless-stopped
    working_dir: /var/www
    volumes:
      - ./:/var/www
      - ./docker/php/local.ini:/usr/local/etc/php/conf.d/local.ini
    networks:
      - qaya-network
    depends_on:
      - db
      - redis

  nginx:
    image: nginx:alpine
    container_name: qaya-hrm-nginx
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./:/var/www
      - ./docker/nginx/conf.d/:/etc/nginx/conf.d/
      - ./docker/nginx/ssl/:/etc/nginx/ssl/
    networks:
      - qaya-network
    depends_on:
      - app

  db:
    image: mysql:8.0
    container_name: qaya-hrm-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: qaya_hrm
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_USER: qaya_user
      MYSQL_PASSWORD: qaya_password
    volumes:
      - dbdata:/var/lib/mysql
    networks:
      - qaya-network

  redis:
    image: redis:alpine
    container_name: qaya-hrm-redis
    restart: unless-stopped
    networks:
      - qaya-network

  queue:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: qaya-hrm-queue
    restart: unless-stopped
    command: php artisan queue:work --sleep=3 --tries=3
    working_dir: /var/www
    volumes:
      - ./:/var/www
    networks:
      - qaya-network
    depends_on:
      - db
      - redis

networks:
  qaya-network:
    driver: bridge

volumes:
  dbdata:
    driver: local
```

**Deploy with Docker**:
```bash
docker-compose up -d
docker-compose exec app php artisan migrate --force
docker-compose exec app php artisan db:seed --force
```

---

### Method 3: Cloud Deployment (AWS)

#### AWS Infrastructure

**Services Used**:
- **EC2**: Application servers
- **RDS**: MySQL database
- **ElastiCache**: Redis cache
- **S3**: File storage
- **CloudFront**: CDN
- **Route 53**: DNS
- **ALB**: Load balancer
- **ACM**: SSL certificates

**Architecture**:
```
┌─────────────────────────────────────────────────┐
│ Route 53 (DNS)                                   │
└──────────────┬──────────────────────────────────┘
               │
┌──────────────▼──────────────────────────────────┐
│ CloudFront (CDN)                                 │
└──────────────┬──────────────────────────────────┘
               │
┌──────────────▼──────────────────────────────────┐
│ Application Load Balancer (ALB)                  │
└──────────────┬──────────────────────────────────┘
               │
       ┌───────┴───────┐
       │               │
┌──────▼─────┐  ┌──────▼─────┐
│ EC2 (App1) │  │ EC2 (App2) │
└──────┬─────┘  └──────┬─────┘
       │               │
       └───────┬───────┘
               │
       ┌───────┴───────┐
       │               │
┌──────▼─────┐  ┌──────▼─────┐
│ RDS MySQL  │  │ ElastiCache│
└────────────┘  └────────────┘
```

---

## Post-Deployment Tasks

### 1. Security Hardening

**Firewall Configuration**:
```bash
# UFW (Ubuntu)
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```

**Disable Root Login**:
```bash
sudo nano /etc/ssh/sshd_config
# Set: PermitRootLogin no
sudo systemctl restart sshd
```

**Install Fail2Ban**:
```bash
sudo apt install -y fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
```

### 2. Monitoring Setup

**Install Monitoring Tools**:
```bash
# New Relic, Datadog, or custom monitoring
```

**Application Monitoring**:
- Error tracking (Sentry, Bugsnag)
- Performance monitoring
- Uptime monitoring
- Log aggregation

### 3. Backup Configuration

**Database Backup Script**:

Create `/usr/local/bin/backup-qaya-db.sh`:
```bash
#!/bin/bash
BACKUP_DIR="/backups/qaya-hrm"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="qaya_hrm"
DB_USER="qaya_user"
DB_PASS="strong_password_here"

mkdir -p $BACKUP_DIR
mysqldump -u $DB_USER -p$DB_PASS $DB_NAME | gzip > $BACKUP_DIR/db_$DATE.sql.gz

# Keep only last 30 days
find $BACKUP_DIR -name "db_*.sql.gz" -mtime +30 -delete
```

**Make Executable**:
```bash
sudo chmod +x /usr/local/bin/backup-qaya-db.sh
```

**Schedule Backup**:
```bash
sudo crontab -e
# Add: 0 2 * * * /usr/local/bin/backup-qaya-db.sh
```

### 4. Performance Optimization

**PHP-FPM Tuning**:

Edit `/etc/php/8.2/fpm/pool.d/www.conf`:
```ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
```

**MySQL Tuning**:

Edit `/etc/mysql/mysql.conf.d/mysqld.cnf`:
```ini
[mysqld]
max_connections = 200
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
query_cache_size = 0
query_cache_type = 0
```

**Redis Configuration**:

Edit `/etc/redis/redis.conf`:
```ini
maxmemory 512mb
maxmemory-policy allkeys-lru
```

---

## Deployment Checklist

### Pre-Deployment

- [ ] Server provisioned and configured
- [ ] Domain name configured
- [ ] SSL certificate obtained
- [ ] Database created and secured
- [ ] Environment variables configured
- [ ] Dependencies installed
- [ ] Application tested locally

### Deployment

- [ ] Code deployed to server
- [ ] Migrations run successfully
- [ ] Seeders run (if needed)
- [ ] Storage linked
- [ ] Permissions set correctly
- [ ] Web server configured
- [ ] Queue workers running
- [ ] Cron jobs configured

### Post-Deployment

- [ ] Application accessible via domain
- [ ] SSL working correctly
- [ ] Login functionality tested
- [ ] Email sending tested
- [ ] File uploads working
- [ ] Queue processing verified
- [ ] Backups configured
- [ ] Monitoring setup
- [ ] Documentation updated
- [ ] Team notified

---

## Maintenance

### Regular Tasks

**Daily**:
- Monitor application logs
- Check queue status
- Verify backups completed

**Weekly**:
- Review error logs
- Check disk space
- Monitor performance metrics
- Review security logs

**Monthly**:
- Update dependencies
- Review and rotate logs
- Test backup restoration
- Security audit
- Performance review

### Updates and Patches

**Update Process**:
```bash
# 1. Backup
./backup-qaya-db.sh

# 2. Enable maintenance mode
php artisan down

# 3. Pull latest code
git pull origin main

# 4. Update dependencies
composer install --optimize-autoloader --no-dev
npm install
npm run build

# 5. Run migrations
php artisan migrate --force

# 6. Clear and rebuild cache
php artisan cache:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 7. Restart services
sudo supervisorctl restart qaya-hrm-worker:*
sudo systemctl restart php8.2-fpm
sudo systemctl restart nginx

# 8. Disable maintenance mode
php artisan up

# 9. Verify application
curl https://hrm.yourcompany.com
```

---

## Troubleshooting Deployment

### Common Issues

**Issue**: 500 Internal Server Error
```bash
# Check logs
tail -f /var/log/nginx/qaya-hrm-error.log
tail -f /var/www/qaya-hrm/storage/logs/laravel.log

# Check permissions
sudo chown -R www-data:www-data /var/www/qaya-hrm
sudo chmod -R 775 /var/www/qaya-hrm/storage
```

**Issue**: Database connection failed
```bash
# Test connection
mysql -u qaya_user -p qaya_hrm

# Check .env configuration
cat .env | grep DB_
```

**Issue**: Queue not processing
```bash
# Check supervisor status
sudo supervisorctl status

# Restart workers
sudo supervisorctl restart qaya-hrm-worker:*
```

**Issue**: Assets not loading
```bash
# Rebuild assets
npm run build

# Clear cache
php artisan cache:clear
```

---

## Rollback Procedure

**Steps**:
```bash
# 1. Enable maintenance mode
php artisan down

# 2. Restore database backup
gunzip < /backups/qaya-hrm/db_YYYYMMDD_HHMMSS.sql.gz | mysql -u qaya_user -p qaya_hrm

# 3. Checkout previous version
git checkout previous-tag

# 4. Restore dependencies
composer install --optimize-autoloader --no-dev

# 5. Clear cache
php artisan cache:clear
php artisan config:cache

# 6. Disable maintenance mode
php artisan up
```

---

## Scaling Considerations

### Horizontal Scaling

**Load Balancer Setup**:
- Multiple application servers
- Shared file storage (NFS/S3)
- Centralized session storage (Redis)
- Database read replicas

### Vertical Scaling

**Resource Upgrades**:
- Increase server CPU/RAM
- Upgrade database instance
- Increase Redis memory
- Optimize application code

---

**Last Updated**: February 2026
