#!/bin/bash

echo "🚀 DEPLOYING TO STAGING SERVER..."
echo "================================================"
echo "📅 Deployment started at: $(date)"
echo "👤 Deployed by: $(whoami)"
echo "📍 Current directory: $(pwd)"
echo "📂 Git branch: $(git branch --show-current 2>/dev/null || echo 'unknown')"
echo "📝 Git commit: $(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')"
echo "================================================"
echo ""

# Step 1: Clear all caches completely
echo "1. Clearing all caches..."
php artisan cache:clear
php artisan config:clear  
php artisan route:clear
php artisan view:clear
php artisan event:clear
php artisan queue:clear

# Step 2: Clear compiled files
echo "2. Clearing compiled files..."
rm -rf bootstrap/cache/*.php
rm -rf storage/framework/cache/data/*
rm -rf storage/framework/sessions/*
rm -rf storage/framework/views/*

# Step 3: Recreate optimize for production
echo "3. Rebuilding optimized files..."
php artisan config:cache
php artisan route:cache  
php artisan view:cache
php artisan event:cache

# Step 4: Check permissions
echo "4. Fixing permissions..."
chmod -R 755 storage
chmod -R 755 bootstrap/cache
chown -R www-data:www-data storage
chown -R www-data:www-data bootstrap/cache

# Step 5: Rebuild frontend assets
echo "5. Building frontend assets for production..."
npm run build:ssr

# Step 6: Restart PM2 processes
echo "6. Restarting PM2 processes..."
if command -v pm2 &> /dev/null; then
    pm2 restart all
    pm2 save
    echo "   ✅ PM2 processes restarted"
else
    echo "   ⚠️  PM2 not found, skipping..."
fi

# Step 7: Restart PHP-FPM service
echo "7. Restarting PHP-FPM..."
PHP_VERSION=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;")
if systemctl list-units --type=service | grep -q "php${PHP_VERSION}-fpm"; then
    sudo systemctl restart php${PHP_VERSION}-fpm
    echo "   ✅ PHP ${PHP_VERSION}-FPM restarted"
else
    # Try common service names
    for service in php-fpm php8.2-fpm php8.1-fpm php8.0-fpm; do
        if systemctl list-units --type=service | grep -q "$service"; then
            sudo systemctl restart $service
            echo "   ✅ $service restarted"
            break
        fi
    done
fi

# Step 8: Restart Apache/Nginx
echo "8. Restarting web server..."
if systemctl list-units --type=service | grep -q "apache2"; then
    sudo systemctl restart apache2
    echo "   ✅ Apache2 restarted"
elif systemctl list-units --type=service | grep -q "nginx"; then
    sudo systemctl restart nginx
    echo "   ✅ Nginx restarted"
else
    echo "   ⚠️  No web server found (apache2/nginx)"
fi

# Step 9: Rebuild Laravel caches for production
echo "9. Rebuilding Laravel caches..."
php artisan route:cache
php artisan view:cache
php artisan config:cache

# Step 10: Restart Queue Workers (Supervisor)
echo "10. Restarting queue workers..."
if command -v supervisorctl &> /dev/null; then
    sudo supervisorctl reread
    sudo supervisorctl update
    sudo supervisorctl restart all
    echo "    ✅ Supervisor workers restarted"
else
    echo "    ⚠️  Supervisor not found, manually restart queue workers if needed"
fi

# Step 11: Verify deployment
echo "11. Verifying deployment..."
echo "    📊 Checking queue status..."
php artisan queue:failed | head -5
echo ""

# Step 12: Final status check
echo "12. Final status check..."
echo "    🔍 Checking services..."

# Check Apache/Nginx status
if systemctl is-active --quiet apache2; then
    echo "    ✅ Apache2: Running"
elif systemctl is-active --quiet nginx; then
    echo "    ✅ Nginx: Running"
else
    echo "    ❌ Web server: Not running"
fi

# Check PHP-FPM status
if systemctl is-active --quiet php${PHP_VERSION}-fpm; then
    echo "    ✅ PHP-FPM: Running"
else
    echo "    ⚠️  PHP-FPM: Status unknown"
fi

# Check PM2 status
if command -v pm2 &> /dev/null; then
    PM2_STATUS=$(pm2 list | grep -c "online" || echo "0")
    echo "    ✅ PM2: $PM2_STATUS processes online"
fi

# Check Supervisor status
if command -v supervisorctl &> /dev/null; then
    SUPERVISOR_STATUS=$(sudo supervisorctl status | grep -c "RUNNING" || echo "0")
    echo "    ✅ Supervisor: $SUPERVISOR_STATUS workers running"
fi

echo ""
echo "🚀 STAGING DEPLOYMENT COMPLETED!"
echo "================================================"
echo ""
echo "📝 Post-deployment checklist:"
echo "   □ Test contact form functionality"
echo "   □ Check email delivery (queue logs)"
echo "   □ Verify SSL certificate"
echo "   □ Test critical user journeys"
echo "   □ Monitor error logs for 10 minutes"
echo ""
echo "📍 Important files to monitor:"
echo "   - Laravel logs: storage/logs/laravel.log"
echo "   - Apache logs: /var/log/apache2/error.log"
echo "   - PM2 logs: pm2 logs"
echo "   - Queue logs: storage/logs/worker.log"
echo ""
echo "🆘 If issues occur:"
echo "   - Check logs: tail -f storage/logs/laravel.log"
echo "   - Rollback: git checkout previous-commit && ./fix_server_routes.sh"
echo "   - Contact support with error details"
echo ""