# Deployment — Blazma LIMS

## 1. Environment Overview

| Attribute | Value |
|-----------|-------|
| **Framework** | Laravel 12 (PHP 8.2+) |
| **Web Server** | Nginx or Apache (document root: `public/`) |
| **Database** | MySQL |
| **Queue** | Redis + Laravel Horizon |
| **Cache** | Redis (DB 1) / File |
| **Session** | File (`SESSION_DRIVER=file`) |
| **File Storage** | AWS S3 (`blazma.com`, `eu-west-1`) |
| **Email (Prod)** | AWS SES |
| **Email (Dev)** | Log driver |

---

## 2. Required Environment Variables

```dotenv
# Application
APP_NAME=Blazma
APP_ENV=production
APP_KEY=<generated>
APP_DEBUG=false
APP_URL=https://yourdomain.com
APP_TIMEZONE=UTC

# Database
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=blazma
DB_USERNAME=<db_user>
DB_PASSWORD=<db_password>

# Redis
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_DB=0
REDIS_CACHE_DB=1

# Queue
QUEUE_CONNECTION=redis

# AWS
AWS_ACCESS_KEY_ID=<key>
AWS_SECRET_ACCESS_KEY=<secret>
AWS_DEFAULT_REGION=eu-west-1
AWS_BUCKET=blazma.com

# Optional: White-label mode (leave empty for marketplace mode)
PROFILE_ID=

# HESN Plus
HESN_PLUS_KEY=<key>
HESN_PLUS_SECRET=<secret>
HESN_PLU_REQ_TOKEN_URL=https://api.lean.sa/oauth/token

# Payment Gateways (global fallbacks, can be overridden per PROFILE)
TAMARA_API_URL=https://api.tamara.co
TAMARA_API_TOKEN=<token>
PAYFORT_MERCHANT_IDENTIFIER=<id>
PAYFORT_ACCESS_CODE=<code>
TAP_PUBLIC=<key>
TAP_SECRET=<secret>

# AI
OPENAI_API_KEY=<key>

# Scandit
SCANDIT_TOKEN=<token>

# ERP
ERP_DYNAMIC_AUTH=<auth>
ERP_DYNAMIC_HOST=<host>
```

---

## 3. Queue Workers (Production)

### Laravel Horizon (Recommended)
```bash
# Start Horizon (manages multiple queue workers)
php artisan horizon

# Horizon runs workers for all queue connections
# Monitor at: https://yourdomain.com/horizon
```

### Supervisor Config for Horizon:
```ini
[program:blazma-horizon]
process_name=%(program_name)s
command=php /var/www/html/blazmaNew/artisan horizon
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/html/blazmaNew/storage/logs/horizon.log
stopwaitsecs=3600
```

### Alternative: Direct Queue Worker
```bash
php artisan queue:work redis --tries=3 --timeout=90
```

---

## 4. Scheduled Tasks

Add to server crontab:
```cron
* * * * * cd /var/www/html/blazmaNew && php artisan schedule:run >> /dev/null 2>&1
```

Laravel's scheduler (via `routes/console.php`) handles:
- Branch totals caching
- HESN token refresh
- Alert checks
- Payment status polling

---

## 5. Web Server Configuration

### Nginx Config:
```nginx
server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/html/blazmaNew/public;

    index index.php;

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

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

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

---

## 6. Initial Setup Commands

```bash
# 1. Install PHP dependencies
composer install --optimize-autoloader --no-dev

# 2. Install Node dependencies & build frontend
npm install && npm run build

# 3. Generate app key (first time only)
php artisan key:generate

# 4. Run migrations
php artisan migrate --force

# 5. Cache config for production
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 6. Set storage permissions
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache

# 7. Create storage symlink
php artisan storage:link
```

---

## 7. PDF Binaries

The project uses wkhtmltopdf for high-quality PDF generation:
```
/var/www/html/blazmaNew/wkhtmltopdf-buster-amd64   # included in project root
```

Ensure it has execute permissions:
```bash
chmod +x /var/www/html/blazmaNew/wkhtmltopdf-buster-amd64
```

---

## 8. Storage Architecture

```
storage/
├── app/
│   ├── public/          # Local public files (symlinked to public/storage)
│   └── private/         # Private files
├── framework/
│   ├── cache/           # File cache
│   ├── sessions/        # File sessions
│   └── views/           # Compiled Blade templates
└── logs/
    ├── laravel.log      # Application logs
    └── horizon.log      # Queue worker logs

AWS S3 (blazma.com bucket, eu-west-1):
├── reports/             # Generated PDF reports
├── photos/              # Patient photos
├── logos/               # Lab logos
├── signatures/          # Doctor signatures
├── documents/           # Insurance/medical documents
└── attachments/         # Order attachments
```

---

## 9. Monitoring

### Laravel Telescope (Development)
- Available at: `/telescope`
- Monitors: requests, queries, jobs, notifications, mail, exceptions
- **Disabled in production** (dont-discover in composer.json)

### Laravel Horizon (Production Queue Monitoring)
- Available at: `/horizon`
- Monitors: queue workers, job throughput, failures, wait times

### Log Files
```bash
tail -f storage/logs/laravel.log    # Application logs
tail -f storage/logs/horizon.log    # Queue worker logs
```

---

## 10. Security Checklist

| Item | Status |
|------|--------|
| `APP_DEBUG=false` in production | Required |
| `APP_KEY` generated and secure | Required |
| Database credentials not in code | ✅ In .env only |
| AWS credentials restricted | Verify IAM permissions |
| ZATCA private keys secured | Stored in `ZATCA_INTEGRATION` table |
| Telescope disabled in production | ✅ dont-discover |
| CORS configured | ✅ CorsMiddleware |
| SQL injection protection | ✅ Eloquent ORM |
| XSS protection | Blade auto-escaping |

---

## 11. Performance Optimization

```bash
# Production optimization commands
php artisan config:cache          # Cache all config files
php artisan route:cache           # Cache route list
php artisan view:cache            # Cache Blade views
php artisan event:cache           # Cache events/listeners
php artisan optimize              # Run all optimizations

# Clear caches (after deployment)
php artisan optimize:clear
```

### Database Performance:
- Ensure `PROFILE_ID` indexes exist on all business tables (auto-indexed)
- Run `ANALYZE TABLE` periodically on large tables
- `END_USER_LAB_ORDER_PACKAGE` — most queried table, ensure indexes are healthy
- Use `branch_totals_cache` table for dashboard queries (cached by job)

---

## 12. Deployment Workflow (CI/CD)

Recommended steps after each code push:

```bash
git pull origin main
composer install --optimize-autoloader --no-dev
npm install && npm run build
php artisan migrate --force
php artisan optimize
php artisan horizon:terminate        # Gracefully restart Horizon workers
# Supervisor auto-restarts Horizon
```
