#!/bin/bash

# Optocare Eye Centre Laravel Backend Deployment Script - cPanel Optimized
# Simple version for cPanel environments
# Usage: bash cpanel-deploy.sh

echo "🚀 cPanel Laravel Deployment Starting..."
echo "========================================"

# Get current directory
CURRENT_DIR=$(pwd)
echo "Current directory: $CURRENT_DIR"

# Check for artisan file
if [ ! -f "artisan" ]; then
    echo "❌ artisan file not found in current directory"
    echo "📁 Files in current directory:"
    ls -la
    echo ""
    echo "🔍 Looking for artisan file..."
    find . -name "artisan" -type f 2>/dev/null | head -5
    echo ""
    echo "💡 If artisan file is missing, it may not have been uploaded."
    echo "   The artisan file should be in the Laravel root directory."
    echo "   Please check your file upload or try re-uploading the Laravel files."
    echo ""
    echo "🚀 Continuing deployment anyway - some steps may still work..."
    ARTISAN_MISSING=true
else
    echo "✅ Laravel application detected"
    ARTISAN_MISSING=false
fi

# Step 1: Environment setup
echo ""
echo "📝 Step 1: Setting up environment..."

# Force remove any existing .env to prevent conflicts
if [ -f ".env" ]; then
    echo "🗑️  Removing existing .env file to prevent conflicts"
    rm .env
fi

if [ -f ".env.production" ]; then
    cp .env.production .env
    echo "✅ Environment file created from .env.production"
    echo "📧 Email configuration included automatically"
    
    # Verify database configuration
    echo "🔍 Verifying database configuration..."
    if grep -q "DB_DATABASE=" .env; then
        echo "✅ Production database name detected"
    else
        echo "❌ Production database name not found in .env"
    fi
    
elif [ -f ".env.example" ]; then
    cp .env.example .env
    echo "✅ Environment file created from .env.example"
    echo "⚠️  WARNING: Using example environment - database may not work"
    echo "📧 Email configuration included automatically"
else
    echo "❌ No .env.production or .env.example found"
    echo "💡 Please create a .env file with your cPanel database configuration"
    exit 1
fi

# Verify email configuration is present
if [ -f ".env" ] && grep -q "MAIL_HOST" .env; then
    echo "✅ Email configuration detected in .env"
else
    echo "⚠️  Email configuration may be missing from .env"
fi

# Step 2: Clean up PSR-4 non-compliant files
echo ""
echo "🧹 Step 2: Cleaning up PSR-4 non-compliant files..."

# Remove any backup or update files that don't comply with PSR-4
PSR4_CLEANUP_FILES=(
    "app/Http/Controllers/AuthControllerUpdates.php"
    "app/Http/Controllers/StaffControllerUpdates.php"
    "app/Models/UserModelUpdates.php"
)

CLEANUP_COUNT=0
for file in "${PSR4_CLEANUP_FILES[@]}"; do
    if [ -f "$file" ]; then
        rm "$file" 2>/dev/null && echo "🗑️  Removed: $file" && ((CLEANUP_COUNT++))
    fi
done

if [ $CLEANUP_COUNT -eq 0 ]; then
    echo "✅ No PSR-4 non-compliant files found"
else
    echo "✅ Cleaned up $CLEANUP_COUNT PSR-4 non-compliant file(s)"
fi

# Step 3: Composer install
echo ""
echo "📦 Step 3: Installing dependencies..."

# Try composer in different locations
COMPOSER_INSTALLED=false

if composer --version >/dev/null 2>&1; then
    echo "🔍 Found composer in PATH"
    composer install --no-dev --optimize-autoloader --no-interaction
    COMPOSER_INSTALLED=true
elif /usr/local/bin/composer --version >/dev/null 2>&1; then
    echo "🔍 Found composer in /usr/local/bin/"
    /usr/local/bin/composer install --no-dev --optimize-autoloader --no-interaction
    COMPOSER_INSTALLED=true
elif [ -f "composer.phar" ]; then
    echo "🔍 Found composer.phar in current directory"
    php composer.phar install --no-dev --optimize-autoloader --no-interaction
    COMPOSER_INSTALLED=true
else
    echo "⚠️  Composer not found. Downloading..."
    if curl -sS https://getcomposer.org/installer | php; then
        echo "✅ Composer downloaded"
        php composer.phar install --no-dev --optimize-autoloader --no-interaction
        COMPOSER_INSTALLED=true
    else
        echo "❌ Failed to download composer"
        echo "💡 Please install composer manually or contact your hosting provider"
    fi
fi

if [ "$COMPOSER_INSTALLED" = true ]; then
    echo "✅ Dependencies installed"
else
    echo "❌ Dependencies installation failed"
fi

# Step 4: Application key
echo ""
echo "🔑 Step 4: Checking application key..."
if grep -q "APP_KEY=base64:" .env 2>/dev/null; then
    echo "✅ Application key exists"
else
    echo "🔄 Generating application key..."
    php artisan key:generate --force
    echo "✅ Application key generated"
fi

# Step 5: Create storage structure and set permissions
echo ""
echo "🔒 Step 5: Creating storage structure and setting permissions..."

# Create all required storage directories (critical for sessions and cache)
echo "📁 Creating required storage directories..."
mkdir -p storage/framework/sessions
mkdir -p storage/framework/views
mkdir -p storage/framework/cache
mkdir -p storage/framework/cache/data
mkdir -p storage/logs
mkdir -p storage/app/public
mkdir -p bootstrap/cache

echo "✅ Storage directories created"

# Set permissions
chmod -R 755 storage/ 2>/dev/null && echo "✅ Storage permissions set" || echo "⚠️  Could not set storage permissions"
chmod -R 755 bootstrap/cache/ 2>/dev/null && echo "✅ Bootstrap cache permissions set" || echo "⚠️  Could not set bootstrap permissions"

# Extra permissions for critical directories
chmod -R 777 storage/framework/sessions/ 2>/dev/null
chmod -R 777 storage/framework/views/ 2>/dev/null
chmod -R 777 storage/framework/cache/ 2>/dev/null
chmod -R 777 storage/logs/ 2>/dev/null
chmod -R 777 bootstrap/cache/ 2>/dev/null

echo "✅ Critical directories fully writable"

# Step 6: Clear caches (CRITICAL for environment changes)
echo ""
echo "🧹 Step 6: Clearing ALL caches (critical for database connection)..."

# Clear all possible caches that could interfere with database connection
php artisan config:clear 2>/dev/null && echo "✅ Config cache cleared" || echo "⚠️  Config cache clear skipped"
php artisan cache:clear 2>/dev/null && echo "✅ Application cache cleared" || echo "⚠️  Application cache clear skipped"
php artisan route:clear 2>/dev/null && echo "✅ Route cache cleared" || echo "⚠️  Route cache clear skipped"
php artisan view:clear 2>/dev/null && echo "✅ View cache cleared" || echo "⚠️  View cache clear skipped"

# Restart queue worker (important for email notifications)
php artisan queue:restart 2>/dev/null && echo "✅ Queue worker restarted" || echo "⚠️  Queue restart failed (worker may not be running)"

# Remove any cached files manually (in case artisan commands fail)
echo "🗑️  Manually removing cache files..."
rm -rf bootstrap/cache/*.php 2>/dev/null && echo "✅ Bootstrap cache files removed" || echo "⚠️  Bootstrap cache removal skipped"
rm -rf storage/framework/cache/data/* 2>/dev/null && echo "✅ Framework cache cleared" || echo "⚠️  Framework cache clear skipped"
rm -rf storage/framework/views/* 2>/dev/null && echo "✅ View cache files removed" || echo "⚠️  View cache removal skipped"

# Force reload environment
echo "🔄 Testing database connection with new environment..."
if php artisan tinker --execute="echo 'DB Test: ' . DB::connection()->getPdo()->getAttribute(PDO::ATTR_CONNECTION_STATUS);" 2>/dev/null; then
    echo "✅ Database connection test successful"
else
    echo "❌ Database connection test failed - check credentials"
fi

# Step 7: Queue System Setup (CRITICAL for Daily Sales Reports)
echo ""
echo "⚡ Step 7: Queue System Setup for Daily Sales Reports..."
echo "🔄 Creating queue tables for background job processing..."

# Create queue tables if they don't exist
# Check if migration file already exists before creating
if ! ls database/migrations/*_create_jobs_table.php >/dev/null 2>&1; then
    if php artisan queue:table 2>/dev/null; then
        echo "✅ Queue table migration created"
    else
        echo "ℹ️  Queue table migration already exists (handled)"
    fi
else
    echo "ℹ️  Queue table migration file already exists - skipping creation"
fi

if ! ls database/migrations/*_create_failed_jobs_table.php >/dev/null 2>&1; then
    if php artisan queue:failed-table 2>/dev/null; then
        echo "✅ Failed jobs table migration created"
    else
        echo "ℹ️  Failed jobs table migration already exists (handled)"
    fi
else
    echo "ℹ️  Failed jobs table migration file already exists - skipping creation"
fi

echo "🔍 Queue tables will be created with database migrations..."

# Ensure QUEUE_CONNECTION is set to database
if grep -q "^QUEUE_CONNECTION=" .env 2>/dev/null; then
    if grep -q "^QUEUE_CONNECTION=database" .env 2>/dev/null; then
        echo "✅ Queue connection already set to database"
    else
        echo "🔧 Updating queue connection to database..."
        sed -i 's/^QUEUE_CONNECTION=.*/QUEUE_CONNECTION=database/' .env
        echo "✅ Queue connection updated to database"
    fi
else
    echo "QUEUE_CONNECTION=database" >> .env
    echo "✅ Queue connection added to .env"
fi

echo "✅ Queue system configured for database-based jobs (survives restarts)"

# Step 8: Database migrations
echo ""
echo "🗄️  Step 8: Database setup..."

# First, let's troubleshoot the database connection
echo "🔍 Database Connection Troubleshooting:"
echo "Current database configuration:"
grep "^DB_" .env 2>/dev/null || echo "❌ No database configuration found in .env"

# Test basic database connection
echo ""
# Test database connection with Artisan (Idempotent)
echo "🧪 Testing database connection..."
if php artisan tinker --execute="echo DB::connection()->getPdo() ? 'OK' : 'FAIL';" >/dev/null 2>&1; then
    echo "✅ Database connection successful"
else
    echo "❌ Database connection failed - check credentials"
    echo ""
    echo "🔧 Common cPanel Database Issues:"
    echo "1. Database user may not exist or have wrong permissions"
    echo "2. Database name may be incorrect"
    echo "3. Password may have special characters that need escaping"
    echo "4. Database host might not be 'localhost' on some hosts"
    echo ""
    echo "💡 Please check your cPanel MySQL settings and ensure user has ALL PRIVILEGES."
fi

# Check migration status first
echo "🔍 Checking migration status..."
MIGRATION_STATUS=$(php artisan migrate:status 2>&1)

if echo "$MIGRATION_STATUS" | grep -q "No migrations found"; then
    echo "ℹ️  No migrations found - fresh installation"
    NEED_MIGRATION=true
elif echo "$MIGRATION_STATUS" | grep -q "Pending"; then
    echo "ℹ️  Pending migrations detected"
    NEED_MIGRATION=true
else
    echo "ℹ️  All migrations already run - checking for new ones"
    NEED_MIGRATION=false
fi

# Run migrations only if needed
if [ "$NEED_MIGRATION" = true ] || ! php artisan migrate:status >/dev/null 2>&1; then
    echo "🔄 Running database migrations..."
    MIGRATE_OUTPUT=$(php artisan migrate --force 2>&1)
    
    if echo "$MIGRATE_OUTPUT" | grep -q "Nothing to migrate"; then
        echo "✅ Database migrations up to date (nothing to migrate)"
    elif echo "$MIGRATE_OUTPUT" | grep -q "Migrated:"; then
        echo "✅ Database migrations completed"
    elif echo "$MIGRATE_OUTPUT" | grep -qi "already exists"; then
        echo "⚠️  Some migrations already exist - this is normal on re-deployment"
        echo "✅ Continuing with existing database structure"
    else
        echo "❌ Database migrations failed"
        echo "Error output: $MIGRATE_OUTPUT"
        echo ""
        echo "🔧 Migration Failure Troubleshooting:"
        echo "1. Check if database exists in cPanel"
        echo "2. Verify database user has ALL PRIVILEGES"
        echo "3. Test database connection manually"
        echo "4. Check Laravel logs: storage/logs/laravel.log"
        echo ""
        echo "📋 Required cPanel Setup:"
        echo "   Database: [See .env DB_DATABASE]"
        echo "   User: [See .env DB_USERNAME]"
        echo "   Privileges: ALL"
    fi
    
    echo "✅ Database migrations up to date"
fi

# Step 9: Email Configuration Verification
echo ""
echo "📧 Step 9: Email Configuration Verification..."
echo "🔍 Verifying email settings in .env..."

# Check if email configuration exists
if grep -q "MAIL_HOST" .env 2>/dev/null; then
    echo "✅ Email configuration found in .env"
    echo "   Host: $(grep '^MAIL_HOST=' .env 2>/dev/null | cut -d'=' -f2)"
    echo "   From: $(grep '^MAIL_FROM_ADDRESS=' .env 2>/dev/null | cut -d'=' -f2)"
else
    echo "⚠️  Email configuration not found in .env"
    echo "💡 Email notifications will not work without proper SMTP configuration"
fi

# Step 10: Production caching
echo ""
echo "⚡ Step 10: Production optimization..."
php artisan config:cache 2>/dev/null && echo "✅ Config cached" || echo "⚠️  Config cache failed"
php artisan route:cache 2>/dev/null && echo "✅ Routes cached" || echo "⚠️  Route cache failed"
php artisan view:cache 2>/dev/null && echo "✅ Views cached" || echo "⚠️  View cache failed"

# Step 11: Storage link
echo ""
echo "🔗 Step 11: Creating storage link..."
if [ -L "public/storage" ] || [ -d "public/storage" ]; then
    echo "✅ Storage link already exists - skipping"
else
    if php artisan storage:link 2>/dev/null; then
        echo "✅ Storage link created"
    else
        echo "⚠️  Could not create storage link"
    fi
fi

# Step 12: Professional Laravel Scheduler & Cron Setup
echo ""
echo "⏰ Step 12: Professional Laravel Scheduler Setup..."
echo "🔍 Configuring robust cron jobs with crontab markers..."

# Configuration - Easy to modify for specific environments
APP_PATH=$(pwd)
PHP_BIN="php" # Change to specific path if needed, e.g., /usr/local/bin/ea-php81

# Identifiers for the crontab block
MARKER_START="# --- OPTOCARE CRON START ---"
MARKER_END="# --- OPTOCARE CRON END ---"

# Define the cron entries
CRON_ENTRIES=(
    "* * * * * cd $APP_PATH && $PHP_BIN -d register_argc_argv=On artisan schedule:run >> /dev/null 2>&1"
    "55 23 * * * cd $APP_PATH && $PHP_BIN -d register_argc_argv=On artisan report:send-daily >> $APP_PATH/storage/logs/cron-backup.log 2>&1"
    "30 1 * * 1 cd $APP_PATH && $PHP_BIN -d register_argc_argv=On artisan report:send-weekly >> $APP_PATH/storage/logs/cron-backup.log 2>&1"
    "15 0 1 * * cd $APP_PATH && $PHP_BIN -d register_argc_argv=On artisan report:send-monthly >> $APP_PATH/storage/logs/cron-backup.log 2>&1"
    "30 0 1 1,4,7,10 * cd $APP_PATH && $PHP_BIN -d register_argc_argv=On artisan report:send-quarterly >> $APP_PATH/storage/logs/cron-backup.log 2>&1"
    "0 2 1 1 * cd $APP_PATH && $PHP_BIN -d register_argc_argv=On artisan report:send-yearly >> $APP_PATH/storage/logs/cron-backup.log 2>&1"
)

echo "🔧 Preparing crontab update..."

# 1. Get current crontab, excluding our existing block
TMP_CRON="/tmp/optocare_crontab_$(date +%s)"
crontab -l 2>/dev/null | sed "/$MARKER_START/,/$MARKER_END/d" > "$TMP_CRON"

# 2. Append the new block
{
    echo "$MARKER_START"
    for entry in "${CRON_ENTRIES[@]}"; do
        echo "$entry"
    done
    echo "$MARKER_END"
} >> "$TMP_CRON"

# 3. Install the new crontab
if crontab "$TMP_CRON" 2>/dev/null; then
    echo "✅ Professional cron jobs installed/updated successfully"
    echo "📍 Entries managed between markers for clean future updates"
else
    echo "❌ Failed to update crontab. Please check permissions."
    echo "📋 Manual Setup Required in cPanel:"
    for entry in "${CRON_ENTRIES[@]}"; do
        echo "   $entry"
    done
fi

rm -f "$TMP_CRON"

echo ""
echo "🔄 Verification:"
crontab -l 2>/dev/null | grep -A 5 "$MARKER_START"


# Step 13: High-Performance Queue Worker Setup (Blazing Fast Notifications & Bulk Comm)
echo ""
echo "⚡ Step 13: High-Performance Queue Worker Setup..."
echo "🚀 Setting up 'Blazing Fast' workers for Notifications, Bulk SMS, and Emails..."

# Stop any existing queue workers to ensure code updates are loaded
echo "🛑 Restarting queue workers to apply new code..."
php artisan queue:restart 2>/dev/null
pkill -f "php artisan queue:work" 2>/dev/null && echo "✅ Existing queue workers stopped" || echo "ℹ️  No existing queue workers found"

# Start new high-performance queue worker in background
# This covers:
# - default: Order Notifications, Bulk SMS, Bulk Emails (Blazing Fast!)
# - reports: Daily/Weekly/Monthly Clinical & Attendance reports
echo "🚀 Starting High-Performance Workers (Bulk Comm + Notifications + Reports)..."
nohup php artisan queue:work --queue=default,reports --sleep=2 --tries=3 --timeout=600 --daemon >/dev/null 2>&1 &
QUEUE_PID=$!

# Wait a moment for queue worker to start
sleep 3

# Check if queue worker is running
if ps -p $QUEUE_PID > /dev/null 2>&1; then
    echo "✅ High-Performance Workers started successfully (PID: $QUEUE_PID)"
    echo "📊 Bulk SMS, Emails, and Order Notifications are now 'Blazing Fast'"
    echo "📈 Reports will be processed in background correctly"
else
    # Fallback check - maybe PID changed or already running
    if pgrep -f "php artisan queue:work" > /dev/null; then
        echo "✅ Queue workers are confirmed running"
    else
        echo "⚠️  Queue worker may not have started properly"
        echo "💡 Manual fix: php artisan queue:work --queue=default,reports --daemon &"
    fi
fi

# Create a comprehensive queue monitoring script
cat > check-queue-status.sh << 'EOF'
#!/bin/bash
echo "🔍 Reports & Notifications Queue Status"
echo "=========================================="

# Check if queue worker is running
QUEUE_PID=$(ps aux | grep "php artisan queue:work" | grep -v grep | awk '{print $2}' | head -1)

if [ ! -z "$QUEUE_PID" ]; then
    echo "✅ High-Performance Worker is running (PID: $QUEUE_PID)"
    echo "📊 Worker details:"
    ps -p $QUEUE_PID -o pid,ppid,pcpu,pmem,etime,cmd | tail -1
    
    echo ""
    echo "📊 Background Processing System:"
    echo "✅ Processing Notifications & Bulk Comm (default queue)"
    echo "✅ Processing Scheduled Reports (reports queue)"
    echo "⏰ Clinical reports scheduled for 23:50 daily"
    echo "🔄 Auto-retry: 3 attempts with exponential backoff"
    echo "📊 Logs: storage/logs/laravel.log"
    
    # Check pending jobs
    echo ""
    echo "📋 Queue Status (Total Pending):"
    php artisan tinker --execute="echo 'Pending Tasks (Total): ' . DB::table('jobs')->count();" 2>/dev/null || echo "⚠️  Unable to check jobs"
    php artisan tinker --execute="echo 'Failed jobs: ' . DB::table('failed_jobs')->count();" 2>/dev/null || echo "⚠️  Unable to check failed jobs"
    
else
    echo "❌ High-Performance Worker is NOT running"
    echo "⚠️  Notifications & Reports will NOT be processed"
    echo "💡 Start worker now: php artisan queue:work --queue=default,reports --daemon &"
fi

# Check cron jobs
echo ""
echo "⏰ Cron Jobs Status:"
if crontab -l 2>/dev/null | grep -q "artisan schedule:run"; then
    echo "✅ Primary cron (scheduler): Configured"
else
    echo "❌ Primary cron (scheduler): NOT configured"
fi

if crontab -l 2>/dev/null | grep -q "report:send-daily"; then
    echo "✅ Backup cron (23:55): Configured"
else
    echo "❌ Backup cron (23:55): NOT configured"
fi

# Check last report
echo ""
echo "📊 Last Report Status:"
if [ -f "storage/logs/laravel.log" ]; then
    LAST_REPORT=$(grep "Daily report.*completed" storage/logs/laravel.log 2>/dev/null | tail -1)
    if [ ! -z "$LAST_REPORT" ]; then
        echo "✅ Last successful report:"
        echo "   $LAST_REPORT"
    else
        echo "ℹ️  No completed reports found in logs"
    fi
    
    LAST_FAILURE=$(grep "Daily report.*failed" storage/logs/laravel.log 2>/dev/null | tail -1)
    if [ ! -z "$LAST_FAILURE" ]; then
        echo "⚠️  Last failure:"
        echo "   $LAST_FAILURE"
    fi
else
    echo "⚠️  Log file not found"
fi

echo ""
echo "🛠️  Queue Management Commands:"
echo "• Start worker: php artisan queue:work --queue=default,reports --daemon &"
echo "• Restart worker: php artisan queue:restart"
echo "• List failed jobs: php artisan queue:failed"
echo "• Retry all failed: php artisan queue:retry all"
echo "• Test Bulk SMS (Job): php artisan tinker --execute=\"\App\Jobs\SendBulkSmsJob::dispatch(['233...'], '', '', null, [], 1);\""
echo ""
echo "📚 Documentation:"
echo "• Setup: QUICK_SETUP_PRODUCTION_READY.md"
echo "• Troubleshooting: PRODUCTION_RELIABILITY_GUIDE.md"

EOF

chmod +x check-queue-status.sh
echo "✅ Created comprehensive queue monitoring script: ./check-queue-status.sh"

# Final verification
echo ""
echo "🔍 Final Verification:"
echo "======================"

# Check PHP version
PHP_VER=$(php -v | head -n 1 | cut -d " " -f 2)
echo "PHP Version: $PHP_VER"

# Check queue worker
QUEUE_PID=$(ps aux | grep "php artisan queue:work" | grep -v grep | awk '{print $2}' | head -1)
if [ ! -z "$QUEUE_PID" ]; then
    echo "✅ Queue Worker: Running (PID: $QUEUE_PID)"
else
    echo "❌ Queue Worker: Not running"
fi

# Check database
if php artisan migrate:status >/dev/null 2>&1; then
    echo "✅ Database: Connected"
else
    echo "❌ Database: Connection failed"
fi

# Check storage
if [ -w "storage/logs" ]; then
    echo "✅ Storage: Writable"
else
    echo "❌ Storage: Not writable"
fi

# Check security middleware
echo ""
echo "🔒 Security Middleware Check:"
if php artisan route:list | grep -q "public-no-auth" 2>/dev/null; then
    echo "✅ QR Code Public Routes: Configured"
else
    echo "ℹ️  QR Code Public Routes: Not configured (optional feature)"
fi

if grep -q "public-api" app/Http/Kernel.php 2>/dev/null; then
    echo "✅ Public API Middleware: Configured"
else
    echo "ℹ️  Public API Middleware: Not configured (optional)"
fi

# Check email configuration
echo ""
echo "📧 Email Configuration Check:"
if grep -q "^MAIL_HOST=" .env 2>/dev/null; then
    MAIL_HOST=$(grep "^MAIL_HOST=" .env | cut -d'=' -f2)
    echo "✅ Email Host: $MAIL_HOST"
else
    echo "❌ Email Host: Not configured"
fi

if grep -q "^MAIL_USERNAME=" .env 2>/dev/null; then
    MAIL_USER=$(grep "^MAIL_USERNAME=" .env | cut -d'=' -f2)
    echo "✅ Email Username: $MAIL_USER"
else
    echo "❌ Email Username: Not configured"
fi

if grep -q "^NOTIFICATION_MAIL_HOST=" .env 2>/dev/null; then
    NOTIF_HOST=$(grep "^NOTIFICATION_MAIL_HOST=" .env | cut -d'=' -f2)
    echo "✅ Notification Email: $NOTIF_HOST"
else
    echo "⚠️  Notification Email: Not configured (required for admin alerts)"
    echo "   Add to .env: NOTIFICATION_MAIL_HOST=mail.tchallasolutions.com"
fi

# Verify production environment settings for email
echo ""
echo "🔍 Production Environment Verification for Email System:"
echo "APP_ENV: $(grep "^APP_ENV=" .env 2>/dev/null | cut -d'=' -f2 || echo 'not set')"
echo "APP_DEBUG: $(grep "^APP_DEBUG=" .env 2>/dev/null | cut -d'=' -f2 || echo 'not set')"
echo "FRONTEND_URL: $(grep "^FRONTEND_URL=" .env 2>/dev/null | cut -d'=' -f2 || echo 'not set')"

# Test password reset email URL generation
echo ""
echo "🧪 Testing Password Reset Email URL Generation:"
if [ -f "debug_email_config.php" ]; then
    echo "🔄 Running email configuration debug..."
    php debug_email_config.php 2>/dev/null | grep -E "(SUCCESS|ERROR|Generated Reset URL|Detected Frontend URL|FRONTEND_URL is correctly set|FRONTEND_URL is not loaded)" || echo "⚠️  Debug script may need Laravel to be fully loaded"
else
    echo "ℹ️  Debug script not found - you can run it manually: php debug_email_config.php"
fi

# Force production reset (critical for email URL issues)
echo ""
echo "🔥 Force Production Reset (clears stubborn caches)..."
if [ -f "force_production_reset.php" ]; then
    echo "🔄 Running force production reset..."
    php force_production_reset.php 2>/dev/null | head -30 || echo "⚠️  Force reset script may need Laravel to be fully loaded"
else
    echo "ℹ️  Force reset script not found - you can run it manually: php force_production_reset.php"
fi

# Step 14: PDF Headless Engine Setup (Browsershot & Puppeteer)
echo ""
echo "📄 Step 14: Setting up PDF Headless Engine (Browsershot)..."

# Detect Node and NPM paths automatically on the server
NODE_PATH=$(which node 2>/dev/null)
NPM_PATH=$(which npm 2>/dev/null)

if [ -z "$NODE_PATH" ]; then
    echo "⚠️  Node.js NOT found in PATH. Checking common cPanel locations..."
    # Search for ea-php or nvm paths if standard which fails
    NODE0=$(find /usr/local/bin -name "node" -type f 2>/dev/null | head -1)
    NODE_PATH=${NODE0:-"/usr/bin/node"}
fi

if [ -z "$NPM_PATH" ]; then
    NPM0=$(find /usr/local/bin -name "npm" -type f 2>/dev/null | head -1)
    NPM_PATH=${NPM0:-"/usr/bin/npm"}
fi

echo "📍 Detected Node: $NODE_PATH"
echo "📍 Detected NPM: $NPM_PATH"

# Synchronize .env with actual server paths
if [ -f ".env" ]; then
    echo "🔧 Synchronizing .env with detected server paths..."
    # Update NODE_BINARY
    if grep -q "^NODE_BINARY=" .env; then
        sed -i "s|^NODE_BINARY=.*|NODE_BINARY=\"$NODE_PATH\"|" .env
    else
        echo "NODE_BINARY=\"$NODE_PATH\"" >> .env
    fi
    
    # Update NPM_BINARY
    if grep -q "^NPM_BINARY=" .env; then
        sed -i "s|^NPM_BINARY=.*|NPM_BINARY=\"$NPM_PATH\"|" .env
    else
        echo "NPM_BINARY=\"$NPM_PATH\"" >> .env
    fi
    echo "✅ .env synced with server binaries"
fi

# Install Puppeteer and Chrome Headless (Idempotent)
if [ ! -d "node_modules/puppeteer" ]; then
    echo "📦 Installing Puppeteer dependencies (this may take a minute)..."
    npm install puppeteer --save-dev --no-interaction > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "✅ Puppeteer installed"
    else
        echo "❌ Puppeteer installation failed"
    fi
else
    echo "✅ Puppeteer already installed - skipping"
fi

echo "🌐 Ensuring Chrome Headless is installed..."
npx puppeteer install chrome > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ Chrome Headless binary is ready"
else
    echo "⚠️  Chrome installation via npx failed. Checking if already present..."
    # Browsershot might still work if a system chrome is available
fi

echo "✅ PDF Generation Engine (Browsershot) is configured"

echo "🎉 Deployment Complete!"
echo "======================"
echo ""
echo "📊 Background Systems: OPTOCARE READY!"
echo "========================================================================="
echo ""
echo "✅ Deployed Features:"
echo "   • Blazing Fast Queue System (Bulk SMS, Emails, Notifications)"
echo "   • Automated Shift-Aware Staff Checkout"
echo "   • Daily Revenue & Performance Reporting"
echo "   • High-Performance Queue Workers Started"
echo ""
echo "⚠️  CRITICAL: Final Check"
echo "========================================================================="
echo "1️⃣  Monitor Workers: bash check-queue-status.sh"
echo "2️⃣  Check Logs: tail -f storage/logs/laravel.log"
echo ""
echo "🚀 Optocare Eye Centre System is now live and optimized!"


echo "Deployment completed at: $(date)"
echo ""
