# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## 📚 **Story Location for Backend Work**

**Backend-only stories belong in this repository**: `/Users/charlie/code/showprima/docs/stories/`

If a story involves **both backend and frontend changes**, it should be placed in the **core location**: `/Users/charlie/code/docs/stories/`

See `/Users/charlie/code/CLAUDE.md` for complete story organization rules and decision tree.

---

## 🔒 **DATABASE SAFETY PROTOCOLS - CRITICAL**

### **⚠️ MANDATORY: Always Backup Before Database Changes!**

**NEVER run migrations or database-altering operations without backing up first!**

This project includes automated backup/restore tools to ensure data safety. All database operations MUST follow these protocols.

### **Available Database Tools**

#### 1. **Backup Database** (`scripts/backup-db.sh`)
```bash
cd /Users/charlie/code/showprima
./scripts/backup-db.sh
```
**Auto-detects database type** (MySQL or SQLite) from `.env` and routes to appropriate backup script:
- **MySQL:** Creates compressed SQL dumps in `database/backups/mysql/`
- **SQLite:** Creates file copies in `database/backups/`
- Includes metadata, integrity verification, and automatic cleanup (keeps last 10)

#### 2. **Restore Database** (`scripts/restore-db.sh`)
```bash
./scripts/restore-db.sh backup_20251002_143022.sqlite
```
Safely restores from backup with pre-restore safety backup and verification.

#### 3. **Compare Databases** (`scripts/compare-db.sh`)
```bash
./scripts/compare-db.sh backup_20251002_143022.sqlite
```
Shows row count differences, schema changes, and migration differences.

#### 4. **Safe Migration** (`php artisan migrate:safe`)
```bash
php artisan migrate:safe
```
Runs migrations with automatic pre-migration backup.

**Options:**
- `--force` - Skip production confirmation
- `--seed` - Seed database after migration
- `--step=N` - Run only N migrations
- `--skip-backup` - Skip backup (NOT RECOMMENDED)

### **Claude Code Restrictions**

**🚫 Claude MUST NOT perform these operations without explicit user confirmation:**

1. `php artisan migrate` - Use `migrate:safe` instead
2. `php artisan migrate:fresh` - NEVER use with real data
3. `php artisan migrate:refresh` - NEVER use with real data
4. `php artisan db:wipe` - NEVER use without backup
5. Direct SQLite/MySQL schema modifications without backup
6. Deleting backup files

**✅ Claude MUST:**

1. Always use `php artisan migrate:safe` for migrations
2. Confirm backups exist before destructive operations
3. Show restoration commands if operations fail
4. Recommend `./scripts/backup-db.sh` before risky operations
5. Use `./scripts/compare-db.sh` to verify changes

### **Recovery Procedures**

```bash
# If migration fails - restore from backup
./scripts/restore-db.sh backup_YYYYMMDD_HHMMSS.sqlite

# If data corrupted - compare and restore
./scripts/compare-db.sh backup_YYYYMMDD_HHMMSS.sqlite
./scripts/restore-db.sh backup_YYYYMMDD_HHMMSS.sqlite

# List available backups
ls -lh database/backups/
```

**Remember: Data loss is permanent. Always backup before migrations!**

---

## 🏥 **HEALTH CHECK & RECOVERY TOOLS - POST-DEPLOYMENT**

### **⚡ Quick Start: Health Check After Deployment**

**ALWAYS run health check after deployment** to catch issues before they cause problems:

```bash
# Standard health check
./scripts/health-check-comprehensive.sh

# With automated fixes
./scripts/health-check-comprehensive.sh --fix

# Verbose diagnostic mode
./scripts/health-check-comprehensive.sh --verbose
```

### **Health Check Tool** (`scripts/health-check-comprehensive.sh`)

**Purpose:** Comprehensive post-deployment validation that catches common issues automatically

**What It Checks (8 Critical Tests):**
- ✅ **.htaccess Syntax** - Catches syntax errors that cause 500 errors
- ✅ **Composer Autoload** - Detects stale cache ("Class not found" errors)
- ✅ **Laravel Boot** - Verifies application can start
- ✅ **Cache Health** - Checks for stale/missing caches
- ✅ **HTTP Endpoints** - Tests API responses (GET /api/events, /health)
- ✅ **CORS Headers** - Validates CORS configuration for credentials mode
- ✅ **Laravel Logs** - Scans for recent errors
- ✅ **Queue Worker** - Checks if worker is running

**Usage Examples:**
```bash
# After deployment on server
ssh globalgalashow@glo.globalgala.com
cd ~/public_html/dev
./scripts/health-check-comprehensive.sh --test-url=https://dev-api.globalgala.com

# If issues detected, apply automated fixes
./scripts/health-check-comprehensive.sh --fix

# For debugging, get detailed output
./scripts/health-check-comprehensive.sh --verbose

# Local development (skip HTTP tests)
./scripts/health-check-comprehensive.sh --skip-http
```

**Exit Codes:**
- `0` - All checks passed ✅
- `1` - Critical failures detected (deployment broken) ❌
- `2` - Warnings detected (non-critical) ⚠️

**Common Issues Detected:**
1. **.htaccess syntax errors** (e.g., `env=HTTP_ORIGIN` on wrong line)
2. **Stale composer autoload** after git pull
3. **CORS wildcard with credentials** (frontend auth fails)
4. **Missing/stale config cache**
5. **Laravel boot failures**
6. **Recent application errors**

### **Emergency Reset Tool** (`scripts/emergency-reset.sh`)

**Purpose:** Nuclear option for recovering from critical deployment failures

**When To Use:**
- ✅ "Class not found" errors after deployment
- ✅ Mysterious 500 errors after cache operations
- ✅ Laravel won't boot after git pull
- ✅ Composer dependency conflicts
- ✅ Stale autoload cache issues

**What It Does:**
1. Clears all Laravel caches (config, route, view, event, application)
2. Removes bootstrap cache files
3. Rebuilds composer autoload (`--optimize`)
4. Optionally reinstalls entire vendor directory (`--full`)
5. Verifies recovery with boot tests

**Usage Examples:**
```bash
# Standard cache reset (30 seconds)
./scripts/emergency-reset.sh

# Full reset with vendor reinstall (2-5 minutes)
./scripts/emergency-reset.sh --full

# Backup database first (recommended for safety)
./scripts/emergency-reset.sh --backup-first

# Skip confirmation (for automation)
./scripts/emergency-reset.sh --yes

# Full reset with backup and no prompts
./scripts/emergency-reset.sh --full --backup-first --yes
```

**Recovery Workflow:**
```
1. Deployment fails
   ↓
2. Run health check --verbose (diagnose issue)
   ↓
3. Try health check --fix (automated fixes)
   ↓
4. If still broken: emergency-reset.sh (clear all caches)
   ↓
5. If STILL broken: emergency-reset.sh --full (reinstall vendor)
   ↓
6. Run health check again to verify recovery
```

### **Typical Post-Deployment Workflow**

```bash
# 1. Deploy code
ssh user@server
cd ~/public_html/dev
git pull origin dev

# 2. Run health check (catches issues immediately)
./scripts/health-check-comprehensive.sh --verbose

# 3a. If all passed ✅
# Done! Deployment successful

# 3b. If issues detected ⚠️
./scripts/health-check-comprehensive.sh --fix

# 3c. If critical failures ❌
./scripts/emergency-reset.sh

# 3d. If STILL broken after reset
./scripts/emergency-reset.sh --full --backup-first

# 4. Verify recovery
./scripts/health-check-comprehensive.sh
```

### **Integration with Deployment Script**

The health check runs automatically as part of `deploy-dev.sh` (Step 6: Health Check). For manual deployments, **always run the health check** after pulling code.

### **Complete Documentation**

See **`docs/deployment/HEALTH_CHECK_RECOVERY_GUIDE.md`** for:
- Detailed tool usage
- Common issue patterns and fixes
- CI/CD integration examples
- Troubleshooting guide
- Best practices

---

## 🚀 **Deployment Commands**

**📖 See Also:**
- **Core Deployment Guide:** `/Users/charlie/code/docs/PRODUCTION_DEPLOYMENT_GUIDE.md` (Complete reference)
- **Master Deployment Guide:** `docs/deployment/MASTER_DEPLOYMENT_GUIDE.md` (Backend-specific)
- **Cron Strategy:** `docs/deployment/CRON_STRATEGY_MASTER_PLAN.md`
- **Latest Session:** `docs/SESSION_STATUS_2025-11-05_MEDIUM_PRIORITY_FIXES.md`

### **Modular Deployment System (Atomic Design Pattern)**

The deployment system follows **atomic design principles** for maximum reliability and maintainability:

**Architecture:**
- **Atoms** (`_deploy-atoms.sh`): Basic functions (logging, validation, detection)
- **Molecules** (`_deploy-molecules.sh`): Combined operations (backup, cache, migrations)
- **Organisms** (`_deploy-organisms.sh`): Complete workflows (health checks, validation)
- **Main Script** (`deploy-dev.sh`): Orchestrates all components

### **Automated Deployment (Production/Dev Server)**

**Deploy to dev server (fully automated):**
```bash
# SSH into server
ssh globalgalashow@glo.globalgala.com

# Navigate to project
cd ~/public_html/dev

# Run deployment script (handles everything!)
./scripts/deploy-dev.sh

# Or with options:
./scripts/deploy-dev.sh --seed-roles          # Force re-seed roles
./scripts/deploy-dev.sh --branch=main         # Deploy main branch
./scripts/deploy-dev.sh --no-backup           # Skip backup (NOT RECOMMENDED)
./scripts/deploy-dev.sh --skip-checks         # Skip pre-deployment checks
./scripts/deploy-dev.sh --help                # Show all options
```

**What the deploy script does:**
1. ✅ **Pre-Deployment Validation** - Checks environment, database, PHP version, permissions
2. ✅ **Database Backup** - Auto-detects MySQL/SQLite and creates verified backup
3. ✅ **Code Deployment** - Pulls latest code, installs dependencies, clears caches
4. ✅ **Database Deployment** - Runs migrations, seeds roles (if needed)
5. ✅ **Queue Worker Deployment** - Restarts workers with **bulk queue support**
6. ✅ **Post-Deployment Validation** - Verifies Laravel boots, migrations complete
7. ✅ **Health Check** - Tests queue system, email system, worker processes
8. ✅ **Status Report** - Shows deployment metadata and quick actions
9. ✅ **Deployment Log** - Saves timestamped deployment record to `storage/logs/`

### **Deployment Features**

**Smart Environment Detection:**
- Auto-detects cPanel servers and uses PHP 8.1
- Detects Supervisor or falls back to screen sessions
- Identifies MySQL vs SQLite database type
- Validates seeder passwords before deployment

**Safety Features:**
- **Pre-deployment checks** prevent deploying to broken environments
- **Automatic backup** with integrity verification before changes
- **Post-deployment validation** ensures system is functional
- **Deployment state tracking** for future rollback support
- **Seeder password validation** requires secure 12+ character passwords

**Queue Worker Configuration:**
```bash
# Queue priority: critical > default > tickets > bulk
--queue=critical,default,tickets,bulk

# critical: Password resets, 2FA, urgent emails
# default: Transactional emails (order confirmations, tickets)
# tickets: Ticket-specific operations
# bulk: Non-urgent bulk invitations, account setup campaigns
```

### **Queue Worker Management**

```bash
# View running worker
screen -r queue-worker
# Detach: Ctrl+A, then D

# Check queue status
./scripts/queue-monitor.sh

# Check email system health
php artisan email:check

# Restart queue worker
./scripts/start-queue-worker.sh
```

**Important:** Queue workers are automatically managed in screen sessions on servers without Supervisor. The deploy script handles start/stop/restart automatically with **full bulk queue support**.

### **Testing Deployment System**

**Run comprehensive deployment tests:**
```bash
# Test all deployment functions
./scripts/test-deploy.sh

# Verbose output
./scripts/test-deploy.sh --verbose
```

Tests cover:
- ✅ Atomic functions (logging, validation, detection)
- ✅ Molecular operations (backup, migrations, cache)
- ✅ Organism workflows (health checks, validation)
- ✅ Integration (all scripts work together)
- ✅ Backwards compatibility (old configs still work)

### **Deployment Library Reference**

**Using deployment libraries in custom scripts:**

```bash
#!/bin/bash
# Load deployment libraries
source "$(dirname "$0")/_deploy-atoms.sh"
source "$(dirname "$0")/_deploy-molecules.sh"
source "$(dirname "$0")/_deploy-organisms.sh"

# Use atomic functions
log_info "Starting custom operation..."
setup_php_environment
if ! command_exists php; then
    die "PHP not found"
fi

# Use molecular operations
backup_database
run_migrations

# Use organism workflows
if ! health_check; then
    log_error "System is unhealthy"
    exit 1
fi

log_success "Operation complete!"
```

**Common Functions:**

**Atoms:**
- `log_info`, `log_success`, `log_warning`, `log_error` - Colored logging
- `command_exists`, `file_exists`, `dir_exists` - Validation
- `get_php_version`, `get_db_type`, `get_app_env` - Environment detection
- `is_cpanel_server`, `has_supervisor`, `has_screen` - Server detection
- `read_env`, `env_key_exists` - Configuration reading

**Molecules:**
- `backup_database`, `verify_recent_backup` - Backup operations
- `git_pull_branch`, `git_is_clean` - Git operations
- `install_php_dependencies` - Composer operations
- `clear_caches`, `rebuild_config_cache` - Cache operations
- `run_migrations`, `run_seeder` - Database operations
- `start_queue_worker`, `stop_queue_worker`, `restart_queue_worker` - Queue management
- `validate_seeder_passwords` - Security validation

**Organisms:**
- `pre_deployment_checks` - Complete pre-deployment validation
- `post_deployment_validation` - Complete post-deployment validation
- `health_check` - System health check workflow
- `backup_workflow` - Complete backup with verification
- `deploy_code_workflow` - Complete code deployment
- `deploy_database_workflow` - Complete database deployment
- `deploy_queue_workflow` - Complete queue worker deployment
- `deployment_status_report` - Generate status report

---

## Common Development Commands

### Database Commands (USE SAFE VERSIONS)
- **Run migrations**: `php artisan migrate:safe` ⚠️ (NOT `migrate`)
- **Backup database**: `./scripts/backup-db.sh`
- **Restore database**: `./scripts/restore-db.sh <backup_file>`
- **Compare databases**: `./scripts/compare-db.sh <backup_file>`

### Laravel/PHP Commands
- **Create migration**: `php artisan make:migration <name>`
- **Create model**: `php artisan make:model <name>`
- **Create controller**: `php artisan make:controller <name>`
- **Run PHPUnit tests**: `vendor/bin/phpunit`
- **Clear cache**: `php artisan cache:clear`
- **Generate application key**: `php artisan key:generate`

### Node.js/Asset Commands
- **Install dependencies**: `npm install`
- **Development build**: `npm run dev`
- **Watch for changes**: `npm run watch`
- **Production build**: `npm run prod`
- **Hot reload**: `npm run hot`

### Testing Commands
- **Run PHPUnit tests**: `vendor/bin/phpunit`
- **Run Playwright E2E tests**: `npm run test:e2e`
- **Run E2E tests with UI**: `npm run test:e2e:ui`
- **Run comprehensive booking tests**: `npm run test:e2e:comprehensive`
- **Install Playwright browsers**: `npm run test:e2e:install`

### Build Guards
- **Check mix matrix**: `npm run guard:matrix`
- **Check config**: `npm run guard:config`
- **Check bundle size**: `npm run guard:size`

### Email & Queue Commands
- **Start queue worker**: `./scripts/start-queue-worker.sh` ⚠️ **REQUIRED** for emails to send
- **Monitor queue**: `./scripts/queue-monitor.sh`
- **Test email system**: `./scripts/test-email-system.sh`
- **Check email health**: `php artisan email:check`
- **Retry failed emails**: `php artisan queue:retry all`
- **View failed jobs**: `php artisan queue:failed`

---

## 📧 **Email System Architecture**

**CRITICAL: Queue worker MUST be running for emails to send!**

### **Email System Overview**

This project uses a **queue-based email system** for reliability, scalability, and non-blocking email delivery.

**Key Components:**
1. **Mailable Classes** (`app/Mail/*.php`) - Define email templates and content
2. **Queue System** (`database` driver) - Stores pending email jobs
3. **Queue Worker** (background process) - Processes jobs and sends emails
4. **Mailpit** (local SMTP) - Captures emails in development (http://localhost:8025)

### **Email Sending Patterns**

**✅ CORRECT Pattern (All emails use this):**
```php
use App\Mail\WelcomeUserMail;
use Illuminate\Support\Facades\Mail;

// Queue email (automatic retry, non-blocking)
Mail::to($user->email)->queue(new WelcomeUserMail($user));
```

**❌ INCORRECT Pattern (Never use this):**
```php
// Synchronous send (blocks request, no retry, can fail silently)
Mail::to($user->email)->send(new WelcomeUserMail($user));
```

### **All Mailables Implement ShouldQueue**

All 14+ Mailable classes implement `ShouldQueue` for automatic queueing:
- ✅ `WelcomeUserMail` - New user welcome
- ✅ `WelcomeBackMail` - Account setup invitations
- ✅ `PaymentConfirmationMail` - Order confirmations
- ✅ `PasswordResetMail` - Password reset links
- ✅ `GenericTemplateMail` - EmailService emails
- ...and all others

### **Queue Worker - REQUIRED**

**Queue worker MUST be running for emails to send:**

```bash
# Development (one terminal)
./scripts/start-queue-worker.sh

# Or start all services at once
./scripts/start-dev-servers.sh
```

**What happens without queue worker:**
- ❌ Emails are queued to database but **never sent**
- ❌ Jobs accumulate in `jobs` table
- ❌ Users don't receive welcome emails, order confirmations, etc.

### **Development Setup**

**Quick Start:**
```bash
# Start everything at once
./scripts/start-dev-servers.sh

# This starts:
# - Laravel API (http://localhost:8000)
# - Queue Worker (processes emails)
# - Verifies Mailpit is running
```

**Manual Setup:**
```bash
# Terminal 1: Laravel API
php artisan serve

# Terminal 2: Queue Worker (REQUIRED!)
./scripts/start-queue-worker.sh

# Terminal 3 (optional): Monitor queue
./scripts/queue-monitor.sh
```

**View Emails:**
- Open Mailpit UI: http://localhost:8025
- All emails sent in development appear here

### **Testing Emails**

**Comprehensive Test:**
```bash
./scripts/test-email-system.sh
```

Tests:
- ✅ WelcomeUserMail (user registration)
- ✅ WelcomeBackMail (account setup)
- ✅ Queue processing
- ✅ Mailpit integration

**Health Check:**
```bash
php artisan email:check

# With SMTP test
php artisan email:check --send-test
```

### **EmailService Usage**

The `EmailService` class is now queue-based by default:

```php
use App\Services\EmailService;

$emailService = app(EmailService::class);

// Queued by default (recommended)
$emailService->sendEmail(
    recipientEmail: 'user@example.com',
    recipientName: 'John Doe',
    subject: 'Welcome!',
    bodyHtml: '<p>Welcome to Show Prima!</p>',
    bodyText: 'Welcome to Show Prima!',
    senderEmail: 'noreply@showprima.com',
    senderName: 'Show Prima'
);

// Synchronous send (use ONLY for critical/urgent emails)
$emailService->sendEmail(
    // ...same parameters
    forceSync: true  // Sends immediately, blocks request
);
```

### **Monitoring & Debugging**

**Queue Statistics:**
```bash
# Live monitoring
./scripts/queue-monitor.sh

# One-time check
php artisan queue:monitor

# Check specific queue
php artisan queue:monitor default,tickets,critical
```

**Failed Jobs:**
```bash
# View failed jobs
php artisan queue:failed

# Retry all failed jobs
php artisan queue:retry all

# Retry specific job
php artisan queue:retry 12345

# Delete failed job
php artisan queue:forget 12345
```

**Logs:**
```bash
# Application logs
tail -f storage/logs/laravel-$(date +%Y-%m-%d).log | grep -i email

# Queue worker logs (if using start-dev-servers.sh)
tail -f storage/logs/queue-worker.log
```

### **Production Deployment**

**Supervisor Configuration** (Recommended for production):

See `docs/EMAIL_FLAKINESS_QUICK_FIX.md` for complete Supervisor setup.

```bash
# Quick summary:
# 1. Install Supervisor
# 2. Create config: /etc/supervisor/conf.d/showprima-queue.conf
# 3. Start worker:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start showprima-queue-worker:*
```

### **Troubleshooting**

**Problem: Emails not sending**
```bash
# 1. Check if queue worker running
ps aux | grep "queue:work"

# 2. If not running, start it
./scripts/start-queue-worker.sh

# 3. Check pending jobs
php artisan queue:monitor

# 4. Check failed jobs
php artisan queue:failed

# 5. Retry failed jobs
php artisan queue:retry all
```

**Problem: Queue worker stops**
- Queue workers timeout after 1 hour by default
- Use Supervisor (production) to auto-restart
- Use `./scripts/start-dev-servers.sh` (development) to keep running

**Problem: Emails go to spam**
- In development: Use Mailpit (emails never actually send)
- In production: Configure SPF/DKIM/DMARC records
- Consider using transactional email service (Resend, Postmark, SendGrid)

### **Email System Files**

**Mailables:** `app/Mail/*.php`
**Email Service:** `app/Services/EmailService.php`
**Email Templates:** `resources/views/emails/*.blade.php`
**Queue Config:** `config/queue.php`
**Mail Config:** `config/mail.php`
**Scripts:** `scripts/start-queue-worker.sh`, `scripts/queue-monitor.sh`, `scripts/test-email-system.sh`
**Artisan Command:** `app/Console/Commands/EmailCheckCommand.php`

### **Best Practices**

1. ✅ **Always use queues** - All Mailables implement `ShouldQueue`
2. ✅ **Always run queue worker** - Required for emails to send
3. ✅ **Test locally first** - Use `./scripts/test-email-system.sh`
4. ✅ **Monitor queue health** - Use `./scripts/queue-monitor.sh`
5. ✅ **Use Mailpit in dev** - Never send real emails locally
6. ✅ **Retry failed jobs** - Run `php artisan queue:retry all` regularly
7. ✅ **Use Supervisor in prod** - Ensures queue worker always runs
8. ❌ **Never use `Mail::send()` directly** - Always queue for reliability

---

## Architecture Overview

### System Type
Modern event ticketing platform with Laravel 9 backend, Next.js/React frontend apps, comprehensive pricing system, and order line items functionality.

### Multi-App Architecture
This project consists of multiple interconnected applications:

**Backend (Laravel 9)**: `/Users/charlie/code/showprima/`
- API-only Laravel backend serving multiple frontends
- Models in `app/Model/` (non-standard location, not `app/Models/`)
- Controllers in `app/Http/Controllers/API/` for frontend APIs
- RESTful API endpoints for venue management, bookings, and admin operations
- Database: MySQL (`showprima_dev`) for development
- Testing Database: MySQL (`showprima_test`) for automated tests - ensures production parity

**Frontend Apps**: `/Users/charlie/code/showprima-frontend/apps/`
- **Ticketing App** (`/apps/ticketing/`): Next.js 14 customer booking interface
- **Admin App** (`/apps/admin/`): Next.js 14 administrative dashboard
- **Venue Editor**: Integrated venue layout editor with React/Konva
- All apps built with TypeScript, Tailwind CSS, and modern React patterns

### Key Architectural Components

**Modern Booking System Architecture**:
- **Hold-Confirm Pattern**: `SeatReservation` model with TTL-based seat holds
- **Pricing Pipeline**: Custom pricing flows from venue editor → booking interface → database
- **Order Line Items**: Complete invoice system with tickets, fees, taxes as separate line items
- **Payment Integration**: Stripe integration with comprehensive pricing support
- **Real-time Updates**: Live seat availability across admin and customer interfaces

**Database Architecture**:
- **Core Tables**: `events`, `seats`, `seat_reservations`, `orders`, `order_line_items`
- **Pricing Storage**: `price_snapshot` field preserves pricing at booking time
- **UUID System**: Seats identified by UUIDs with human-readable display names
- **Concurrency Protection**: Pessimistic locking with `lockForUpdate()` prevents race conditions
- **Transaction Safety**: All booking operations wrapped in database transactions

**Venue Management System**:
- **Templates**: JSON-based venue templates with sections, tables, individual seats
- **Editor Integration**: React/Konva-based visual venue editor
- **Dynamic Pricing**: Per-seat custom pricing with section-level overrides
- **Spatial System**: Advanced grid placement, rotation, and bulk operations

**Admin Dashboard Features**:
- **Real-time Monitoring**: Live statistics, capacity tracking, revenue analytics
- **Bulk Operations**: Rectangle selection for multi-seat admin actions (shadow sold, blocked, etc.)
- **Order Management**: Complete order tracking with detailed line items breakdown
- **Seat Management**: Visual seat map with admin selection and bulk operations

### Frontend Architecture Details

**Ticketing App** (`/apps/ticketing/`):
- **Framework**: Next.js 14 with App Router and TypeScript
- **Canvas**: React Konva for interactive venue visualization
- **State Management**: Zustand with modular slice architecture
- **Booking Flow**: Seat selection → pricing calculation → hold → confirm
- **Real-time**: Auto-refresh for seat availability updates

**Admin App** (`/apps/admin/`):
- **Framework**: Next.js 14 with TypeScript and Tailwind CSS
- **Dashboard**: Real-time analytics with Server-Sent Events (SSE)
- **Components**: Reusable admin interface components
- **API Integration**: Comprehensive REST API client with error handling
- **Order Line Items**: Professional invoice-style order breakdown display

**Shared Systems**:
- **API Client**: Type-safe API clients with comprehensive error handling
- **Component Reuse**: Shared venue canvas between admin and customer apps
- **Type Safety**: Full TypeScript coverage across all frontend applications

### Critical Business Logic

**Modern Seat Booking Process**:
1. **Hold Phase**: Frontend requests seat hold with custom pricing via `/api/seats/hold`
2. **Pricing Pipeline**: Custom pricing from venue editor flows through `seat_pricing` array
3. **Price Snapshot**: Backend stores `price_snapshot` in `seat_reservations` table
4. **Confirmation**: Frontend confirms booking via `SeatReservation::confirmBooking()`
5. **Order Creation**: Creates `orders` record and detailed `order_line_items`
6. **Line Items Generation**: Automatic breakdown into tickets, fees, taxes as separate line items

**Pricing System**:
- **Venue Editor**: Admins set custom per-seat pricing with visual price labels
- **Booking Interface**: Shows real custom pricing to customers
- **Price Preservation**: `price_snapshot` field captures pricing at hold time
- **Line Items**: Automatic calculation of booking fees (2.5%) and VAT (21%)

**Order Line Items System**:
- **Individual Tickets**: Each seat as separate line item with seat number
- **Calculated Fees**: Service fees automatically calculated as percentage of ticket total
- **Tax Calculation**: VAT calculated on subtotal + fees
- **Invoice Ready**: Complete breakdown suitable for accounting and invoicing

**Admin Operations**:
- **Shadow Sold**: Mark seats as sold without revenue (for comp tickets, staff seating)
- **Seat Blocking**: Remove seats from availability for maintenance, VIP areas
- **Bulk Operations**: Rectangle selection enables batch admin actions
- **Real-time Updates**: Changes immediately reflected across customer interfaces

**Payment Processing**:
- Stripe integration with comprehensive pricing pipeline support
- PayPal and NBE (National Bank of Egypt) integrations available
- Idempotency keys required for all payment operations
- Full pricing breakdown in payment metadata

**Security Features**:
- JWT authentication for API endpoints
- CORS middleware for cross-origin frontend requests
- Rate limiting on booking endpoints with 429 detection
- Emergency kill switches for critical system control

### Testing Strategy

**Test Database Configuration** (Updated 2025-10-31):
- **Database**: MySQL (`showprima_test`) for 100% production parity
- **Connection**: Dedicated `mysql_testing` connection in `config/database.php`
- **PHPUnit Config**: `phpunit.xml` configured to use `mysql_testing` connection
- **Schema Management**: Uses `database/schema/mysql-schema.sql` (104 base tables)
- **Migration Strategy**: `RefreshDatabase` trait runs migrations on clean schema each test

**Test Types**:
- **PHPUnit Unit Tests**: Business logic, services, models (`tests/Unit/`)
- **PHPUnit Feature Tests**: API endpoints, integration flows (`tests/Feature/`)
- **Playwright E2E Tests**: Critical booking flows (workers=1 to prevent race conditions)
- **Page Objects**: Located in `tests/e2e/page-objects/`

**Test Database Setup** (One-time):
```bash
# 1. Create test database
mysql -u root -p << 'EOF'
CREATE DATABASE IF NOT EXISTS showprima_test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
GRANT ALL PRIVILEGES ON showprima_test.* TO 'showprima'@'localhost';
FLUSH PRIVILEGES;
EOF

# 2. Load schema dump (104 base tables)
mysql -u showprima -p showprima_test < database/schema/mysql-schema.sql

# 3. Run October 2025 migrations
php artisan migrate --env=testing --force
```

**Running Tests**:
```bash
# Run all tests
vendor/bin/phpunit

# Run specific test suite
vendor/bin/phpunit tests/Unit/
vendor/bin/phpunit tests/Feature/

# Run with coverage
vendor/bin/phpunit --coverage-text

# Run specific test group (e.g., Revolut payment tests)
vendor/bin/phpunit --group revolut
```

**How RefreshDatabase Works**:
1. Test begins → `RefreshDatabase` trait activates
2. Drops all tables → Loads schema dump → Runs migrations
3. Test executes with fresh database
4. Test ends → Database ready for next test

**Migration Safety** (Added 2025-10-31):
- October 2025 migrations include table existence guards
- Prevents foreign key errors during `migrate:fresh`
- Guards check if required tables exist before altering

**See Also**:
- `docs/payments/qa/DEVOPS_TASK_COMPLETION_SUMMARY.md` - Test DB configuration fix details
- `database/schema/mysql-schema.sql` - Schema dump (regenerate with `php artisan schema:dump`)

## Environment Configuration & Development Servers

### Current Development Setup
**Backend Server (Laravel)**:
- **Primary**: `http://localhost:8000` - Main Laravel API server
- **Secondary**: `http://127.0.0.1:8001` - Backup Laravel server (when port conflicts occur)
- **Database**: MySQL (`showprima_dev`) for all development operations
- **Start Command**: `cd /Users/charlie/code/showprima && php artisan serve --host=localhost --port=8000`

**Frontend Servers (Next.js)**:
- **Ticketing App**: `http://localhost:3002` - Customer booking interface
- **Admin App**: `http://localhost:3001` - Administrative dashboard
- **Start Commands**:
  - Ticketing: `cd /Users/charlie/code/showprima-frontend && npm run dev` (workspace management)
  - Admin: Runs automatically via workspace configuration

**API Integration**:
- Frontend apps connect to `http://localhost:8000/api` for all backend operations
- CORS configured for cross-origin requests
- All pricing and booking data flows through RESTful API endpoints

### Key Development URLs
- **Customer Booking**: `http://localhost:3002/booking/1` (Event ID 1)
- **Venue Editor**: `http://localhost:3002/venue-editor` (Venue layout management)
- **Admin Dashboard**: `http://localhost:3001/` (Real-time monitoring)
- **Admin Orders**: `http://localhost:3001/orders` (Order line items display)

### Node.js Version Management
- Node 18.20.3 (locked via Volta configuration)
- npm 10.8.2
- Dependencies pinned for security (Laravel Mix 5.0.9, Webpack 4.46.0)

### Database & Storage
- **Local Development**: MySQL (`showprima_dev`) for production parity
- **Dev Server**: MySQL (cPanel shared hosting environment)
- **Testing DB**: MySQL (`showprima_test`) for test isolation with production parity
- **Database User**: `showprima@localhost` with full privileges
- **Schema**: Supports complex venues with seats, tables, sections, reservations
- **Line Items**: Complete order breakdown with automatic fee/tax calculation
- **Pricing**: `price_snapshot` field preserves exact pricing at booking time
- **Backup Strategy**: Auto-detects MySQL vs SQLite, creates compressed backups with metadata
- **Test Database Setup**:
  - Run `mysql -u root -p < database/setup-test-database.sql` to create test database
  - Grants privileges to `showprima` user automatically

### PHP Version Requirements
- **Required:** PHP 8.0+ (Laravel 9 + modern dependencies)
- **Local Development:** PHP 8.1+ recommended
- **cPanel/Shared Hosting:** Deploy script auto-detects and uses PHP 8.1
  - Path: `/opt/cpanel/ea-php81/root/usr/bin/php`
  - Automatically prepended to PATH during deployment
- **Extensions Required:** sodium, mbstring, xml, curl, mysql, etc.
- **Platform Requirements:** Deploy script uses `--ignore-platform-reqs` for sodium detection issues on cPanel

### Browser Support
Defined in `.browserslist`:
- `>=0.5%`
- `last 2 versions`
- `not dead`
- `not op_mini all`

## Critical Development Patterns

### Modern Booking Operations
Always use `SeatReservation` model with pricing pipeline support:
```php
// Hold seats with custom pricing
$result = SeatReservation::holdSeats(
    $eventId,
    $seatIds,
    $sessionId,
    $userId,
    $holdToken,
    $expiresAt,
    $correlationId,
    microtime(true),
    $seatPricing  // Critical: Pass frontend pricing data
);

// Confirm booking with line items generation
$confirmResult = SeatReservation::confirmBooking(
    $sessionId,
    $customerName,
    $customerEmail,
    $customerPhone
);
```

### Frontend-Backend Pricing Integration
Always pass custom pricing from frontend to backend:
```typescript
// Frontend: Extract seat pricing
const seatPricing: Record<string, number> = {};
selectedSeats.forEach(seat => {
    seatPricing[seat.db_seat_id || seat.seat_id] = seat.price;
});

// Frontend: Send to hold API
const holdResponse = await fetch(`${API_BASE_URL}/api/seats/hold`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        event_id: eventId,
        seat_ids: seatIds,
        session_id: sessionId,
        seat_pricing: seatPricing  // Critical: Include pricing
    }),
});
```

### Order Line Items Access
Access detailed line items via API endpoint:
```php
// Backend: Line items endpoint
public function getOrderLineItems($orderIdOrSession) {
    // Handles both numeric order IDs and session strings
    $lineItems = \App\OrderLineItem::where('order_id', $orderId)
        ->orderBy('item_type')
        ->get();

    return response()->json([
        'data' => [
            'line_items' => [
                'tickets' => $lineItems->where('item_type', 'ticket'),
                'fees' => $lineItems->where('item_type', 'booking_fee'),
                'taxes' => $lineItems->where('item_type', 'tax'),
                'discounts' => $lineItems->where('item_type', 'discount'),
            ]
        ]
    ]);
}
```

### Time Operations
Always use `TimeProvider` service instead of direct time functions:
```php
// Correct
$timeProvider = app(TimeProvider::class);
$currentTime = $timeProvider->now();

// Incorrect
$currentTime = Carbon::now();
```

### Error Handling
Follow Laravel patterns with proper HTTP status codes:
- 409 for seat conflicts
- 422 for validation errors  
- 404 for not found resources
- 500 for server errors

### Logging
Use structured logging with correlation IDs:
```php
Log::error('Booking conflict detected', [
    'event_id' => $eventId,
    'seat' => $seat,
    'user_id' => $userId,
    'correlation_id' => $correlationId
]);
```

## Security Considerations
- Never commit secrets (use `.env` files)
- Use idempotency keys for booking/payment operations
- Validate all inputs with Laravel Form Requests
- Apply rate limiting to booking endpoints
- Use emergency kill switches for critical system control

---

## 🔀 **Git Workflow & CI/CD Best Practices**

**CRITICAL: Branch Strategy - NEVER push directly to `main` unless explicitly instructed.**

This project follows a proper Git branching strategy aligned with the frontend monorepo at `/Users/charlie/code/showprima-frontend/`.

### **Branch Structure**
- **`main`** - Production-ready code, protected branch
- **`staging`** - Pre-production testing environment
- **`dev`** - Active development integration branch
- **`feature/*`** - Individual feature branches (e.g., `feature/order-line-items`, `feature/stripe-integration`)
- **`fix/*`** - Bug fix branches (e.g., `fix/pricing-pipeline-bug`)
- **`hotfix/*`** - Emergency production fixes

### **Standard Development Workflow**

```bash
# 1. Start new feature from dev branch
git checkout dev
git pull origin dev
git checkout -b feature/your-feature-name

# 2. Make changes and commit regularly
git add .
git commit -m "feat: descriptive commit message"

# 3. Push feature branch
git push -u origin feature/your-feature-name

# 4. Create PR to merge into dev
# (Use GitHub UI or gh CLI)

# 5. After PR approval, merge to dev
# Then create PR from dev → staging → main
```

### **Branch Progression**
```
feature/* → dev → staging → main
   ↓         ↓       ↓        ↓
 Active   Integration  QA   Production
```

### **Commit Message Conventions**
Use conventional commits for clear history and changelog generation:
- `feat:` - New features (e.g., `feat: implement order line items system`)
- `fix:` - Bug fixes (e.g., `fix: resolve pricing pipeline scope issue`)
- `chore:` - Maintenance tasks (e.g., `chore: update dependencies`)
- `docs:` - Documentation updates (e.g., `docs: add pricing system architecture`)
- `refactor:` - Code refactoring (e.g., `refactor: optimize seat reservation logic`)
- `test:` - Test additions/updates (e.g., `test: add E2E booking flow tests`)
- `perf:` - Performance improvements (e.g., `perf: add database query caching`)
- `db:` - Database migrations (e.g., `db: add order_line_items table`)

### **Rules & Guardrails**
- ✅ **Always work on feature branches** - Never commit directly to `dev`, `staging`, or `main`
- ✅ **Pull latest dev before creating feature branch** - Avoid merge conflicts
- ✅ **Create PRs for all changes** - Enable code review and CI checks
- ✅ **Test locally before pushing** - Run PHPUnit tests and verify migrations
- ✅ **Keep commits atomic** - One logical change per commit
- ✅ **Backup before database changes** - Use `./scripts/backup-db.sh` before migrations
- ✅ **Use safe migrations** - Always use `php artisan migrate:safe` instead of `migrate`

- ❌ **Never push directly to main** - Unless explicitly instructed for emergency hotfixes
- ❌ **Never force push to shared branches** - Avoid `git push --force` on `dev`, `staging`, `main`
- ❌ **Don't merge without review** - Wait for PR approval
- ❌ **Don't commit broken code** - Ensure tests pass locally first
- ❌ **Don't skip database backups** - Always backup before migrations or schema changes
- ❌ **Don't commit .env files** - Keep secrets out of version control

### **Backend-Specific Considerations**
- **Database Migrations**: All migration PRs must include backup verification
- **API Changes**: Document breaking changes in commit messages and PR descriptions
- **Testing**: Run full test suite (`vendor/bin/phpunit`) before pushing
- **Dependencies**: Document any new Composer packages in PR description
- **Configuration**: Never commit environment-specific config (use `.env.example` as template)

### **Cross-Repository Coordination**
When changes span both backend and frontend:
1. Create feature branches with matching names in both repos (e.g., `feature/booking-flow`)
2. Reference related PRs in descriptions (e.g., "Related frontend PR: showprima-frontend#123")
3. Coordinate merge timing to avoid API mismatches
4. Test integration locally before creating PRs

### **Emergency Hotfix Workflow**
```bash
# Only for critical production issues
git checkout main
git pull origin main
git checkout -b hotfix/critical-issue-name

# Make minimal fix
git add .
git commit -m "hotfix: critical issue description"

# Push and create PR to main
git push -u origin hotfix/critical-issue-name

# After merge, backport to dev and staging
git checkout dev
git merge main
git push origin dev
```

## Recent Development Log

### 2025-10-20: Web Routes Cleanup - Removed Legacy Controllers

**Removed Legacy Web Routes:**
- ✅ **47% Reduction**: Removed 269 lines of dead routes (571 → 302 lines)
- ✅ **Clean Route List**: No more ReflectionException errors from missing controllers
- ✅ **Production Ready**: All removed routes reference controllers that no longer exist

**Controllers Removed:**
- **Frontend\*** - Event booking, cart, checkout, PayPal callbacks (40 lines)
- **Auth & Account** - Login, registration, password reset (18 lines)
- **Dashboard\*** - Admin panel, events, tickets, venues, reports, CMS (274 lines)
- **Boxoffice\*** - Ticket scanning, check-in (part of Dashboard group)

**Active Routes Preserved (302 lines):**
- `/health`, `/ready`, `/metrics` - Health monitoring
- `/scanner` - Ticket scanner web app
- `/monitoring` - Internal monitoring dashboard
- `/__test/*` - Test-only endpoints (gated)
- `/clear-cache` - Cache management utility
- `/newsletter/*` - Newsletter subscription (rate limited)
- `/email-preview/*` - Email template preview (dev only)
- `/support-donate/*` - Fundraising public pages (Fundraising\PublicPageController)
- `/{identifier}` - PageController catchall routing

**Why Removed:**
- All frontend functionality moved to Next.js apps (localhost:3001, localhost:3002)
- Authentication moved to JWT API (routes/api/admin/auth.php, routes/api/customer.php)
- Admin functionality moved to Next.js admin app + API routes (routes/api/admin/*.php)
- Legacy blade-based system fully replaced

**Git Branch:**
- `cleanup/remove-legacy-web-routes` (3 commits, ready for merge to dev)

**Files Changed:**
- `routes/web.php` - Reduced from 571 to 302 lines
- Created backup at `routes/web.php.backup.20251020_141807`

---

### 2025-10-16: MySQL for All Environments (Development & Testing)

**Complete MySQL Migration:**
- ✅ **Full MySQL Adoption**: Now using MySQL for both development AND testing environments
- ✅ **Production Parity**: Both local dev and tests match production environment exactly
- ✅ **Eliminated SQLite**: Removed all SQLite references to reduce confusion
- ✅ **Test Database**: Created dedicated `showprima_test` database for isolated testing

**Database Configuration:**
- **Development**: MySQL (`showprima_dev`) with user `showprima@localhost`
- **Testing**: MySQL (`showprima_test`) with user `showprima@localhost`
- **Homebrew MySQL**: Installed via `brew install mysql` on macOS

**Setup Instructions:**
- **Test Database**: Run `mysql -u root -p < database/setup-test-database.sql` to create test database
- **PHPUnit Configuration**: Updated `phpunit.xml` to use MySQL instead of SQLite in-memory
- **Migrations**: Same migrations work for both dev and test databases

**Benefits Achieved:**
- **100% Production Parity**: No more SQLite vs MySQL compatibility issues
- **Consistent Testing**: Tests run on same database engine as production
- **Simpler Setup**: One database system instead of two
- **Better Data Integrity**: All environments use MySQL constraints and features

**Files Updated:**
- `phpunit.xml` - Changed from SQLite to MySQL for testing
- `CLAUDE.md` - Updated all references from SQLite to MySQL
- `database/setup-test-database.sql` - New SQL script for test database setup

### 2025-09-26: Initial MySQL Migration for Development

**Major Infrastructure Upgrade:**
- ✅ **SQLite → MySQL Migration**: Migrated from SQLite to MySQL for local development
- ✅ **Production Parity**: Local development matches cPanel production environment (MySQL)
- ✅ **Analytics Fixed**: MySQL-specific SQL functions (`HOUR()`, `DATE()`, `JSON_EXTRACT()`) now work correctly
- ✅ **Data Integrity**: All 1,377+ records migrated successfully (1,155 seats, 199 reservations, 23 orders)

**Files Created:**
- `app/Console/Commands/MigrateSqliteToMysql.php` - Data migration tool (now legacy)
- `app/Console/Commands/VerifyDatabaseMigration.php` - Migration verification (now legacy)
- `.env` - MySQL connection configuration

### 2025-09-24: Critical Pricing Pipeline & Order Line Items System

**Major System Enhancements:**
- ✅ **Critical Pricing Fix**: Resolved complete pricing pipeline disconnection between venue editor custom pricing and actual checkout/database pricing
- ✅ **Order Line Items System**: Implemented comprehensive invoice-style order breakdown with individual tickets, fees, taxes as separate line items
- ✅ **Admin Interface Integration**: Complete line items display in admin dashboard with professional invoice-quality presentation
- ✅ **Pricing Pipeline**: Custom pricing now flows correctly from venue editor → booking interface → checkout → order database
- ✅ **Database Architecture**: Added `order_line_items` table with proper foreign key relationships and automatic line item generation

**Critical Technical Resolution:**
- **Scope Bug Fix**: Fixed `$seatPricing` parameter not in closure scope (line 98 of SeatReservation.php) - root cause of all pricing issues
- **API Enhancement**: Enhanced `/api/seats/hold` endpoint to accept and process `seat_pricing` array from frontend
- **Frontend Integration**: Updated booking service to extract and pass seat pricing data to backend
- **Price Preservation**: Implemented `price_snapshot` field to store exact pricing at booking time
- **Line Items Generation**: Automatic creation of ticket, fee, and tax line items during booking confirmation

**Business Logic Implementation:**
- **Individual Ticket Items**: Each seat creates separate line item with seat number and metadata
- **Calculated Fees**: Automatic booking fee calculation (2.5% of ticket subtotal)
- **Tax Calculation**: VAT calculation (21% of subtotal + fees)
- **Admin Operations**: Shadow sold, blocked, bulk operations with rectangle selection
- **Invoice Ready**: Complete breakdown suitable for accounting and customer invoicing

**Frontend Architecture:**
- **Admin Dashboard**: Professional line items display with loading states and error handling
- **API Integration**: Comprehensive REST client with proper error handling and type safety
- **Legacy Support**: Graceful fallback for orders created before line items system
- **Mobile Responsive**: Full functionality across all device sizes

**Current System State:**
- **Working Example**: Order `iToLaAdxnU8W70WgYTxVOEvssPHq60xEaqt6leK8` demonstrates complete €18.61 breakdown
- **Pricing Accuracy**: Custom pricing (€10.00, €5.00) flows correctly to final invoice
- **Fee Calculation**: Service Fee €0.38 (2.5%) and VAT €3.23 (21%) calculated automatically
- **Professional Display**: Invoice-quality breakdown with print/issue invoice capabilities

### 2025-09-17: Frontend Booking System Integration

**Completed Integration:**
- ✅ **Full-Stack Integration**: Connected React/Next.js frontend with Laravel backend APIs
- ✅ **Complex Seating Support**: Venue templates with tables, sections, and child seats
- ✅ **Seat Synchronization**: `SyncVenueSeats` command for template-database sync
- ✅ **Real-time Availability**: Accurate seat booking status via `seat_reservations` table
- ✅ **CORS Configuration**: Fixed middleware for frontend API access

**Architecture Foundation:**
- Venue templates with JSON-based seat layout storage
- Database synchronization via artisan commands
- Real-time seat status updates with visual feedback
- Test mode for production-level database testing
### 2025-10-22: Production Deployment Automation & Email System QA

**Deployment Infrastructure:**
- ✅ **Automated Deploy Script**: One-command deployment (`./scripts/deploy-dev.sh`)
- ✅ **MySQL Backup Auto-Detection**: Automatically detects and backs up MySQL (not SQLite)
- ✅ **PHP 8.1 Auto-Detection**: Detects and uses PHP 8.1 on cPanel servers
- ✅ **Smart Role Seeding**: Only seeds roles when table is empty (use `--seed-roles` to force)
- ✅ **Queue Worker Management**: Automatic restart in screen sessions (no manual management)
- ✅ **Health Verification**: Post-deployment checks for queue and email systems

**Security Improvements:**
- ✅ **Secure Database Access**: Created `scripts/_db-helper.sh` - credentials from `.env`, not command line
- ✅ **Password Exposure Fixed**: Eliminated MySQL passwords from process list (`ps aux`)
- ✅ **5 Scripts Secured**: queue-worker, queue-monitor, test-email, dev-servers, cron health check

**Email System QA Completion:**
- ✅ **All Mail::send() Fixed**: Changed 11+ locations to use `Mail::queue()`
- ✅ **forceSync Guidelines**: Comprehensive 500+ line guide for EmailService usage
- ✅ **Environment Validation**: Script to check APP_ENV, APP_DEBUG, database config
- ✅ **QA Grade Upgrade**: A- → **A+** (all critical/high issues resolved)

**MySQL utf8mb4 Compliance:**
- ✅ **Index Length Limits**: All indexed strings ≤191 chars (764 bytes < 767 byte limit)
- ✅ **3 Migrations Fixed**: venue_themes, cms_files, account_setup_invitations
- ✅ **Production Ready**: Tested on fresh MySQL database, zero errors

**Documentation Created:**
- `docs/DEPLOYMENT_GUIDE.md` - Comprehensive deployment guide
- `docs/DEPLOY_QUICK_REFERENCE.md` - Quick reference card
- `docs/EMAIL_SERVICE_FORCE_SYNC_GUIDELINES.md` - forceSync usage (500+ lines)
- `docs/QA_COMPLETION_SUMMARY.md` - QA completion report
- `docs/EMAIL_SYSTEM_QA_REVIEW.md` - Complete QA review

**Deployment Features:**
1. Auto-detects and backs up MySQL database (compressed SQL dumps)
2. Pulls latest code from dev branch
3. Installs dependencies with platform requirement workarounds
4. Auto-detects and uses PHP 8.1 on cPanel servers
5. Clears and rebuilds caches
6. Runs database migrations safely
7. Seeds roles/permissions (only when needed)
8. Restarts queue workers in screen session automatically
9. Verifies deployment health (queue + email checks)

**Production Server Environment:**
- **Hosting**: cPanel shared hosting (glo.globalgala.com)
- **PHP**: Auto-detected PHP 8.1 (`/opt/cpanel/ea-php81/root/usr/bin/php`)
- **Database**: MySQL with compressed backups
- **Queue Workers**: Managed in screen sessions (automatic restart on deploy)
- **Deploy Command**: `./scripts/deploy-dev.sh` (fully automated)
