#!/bin/bash

# GengSewa Production Deployment Script
# Quick deployment with all optimizations

set -e # Exit on error

echo "======================================"
echo "GengSewa Production Deployment"
echo "======================================"
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_info() {
    echo -e "→ $1"
}

# Check if .env file exists
if [ ! -f .env ]; then
    print_error ".env file not found!"
    exit 1
fi

# 1. Enable maintenance mode
print_info "Enabling maintenance mode..."
php artisan down --retry=60
print_success "Maintenance mode enabled"

# 2. Pull latest code (if using git)
if [ -d .git ]; then
    print_info "Pulling latest code..."
    git pull origin main || print_warning "Git pull failed or not configured"
fi

# 3. Install/Update dependencies
print_info "Installing composer dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction
print_success "Composer dependencies installed"

# 4. Run migrations
print_info "Running database migrations..."
php artisan migrate --force
print_success "Migrations completed"

# 5. Clear all caches
print_info "Clearing all caches..."
php artisan optimize:clear
print_success "Caches cleared"

# 6. Optimize application
print_info "Optimizing application..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
print_success "Application optimized"

# 7. Optimize autoloader
print_info "Optimizing autoloader..."
composer dump-autoload --optimize --classmap-authoritative --no-interaction
print_success "Autoloader optimized"

# 8. Build frontend assets
if [ -f "package.json" ]; then
    print_info "Building frontend assets..."
    if [ -d "node_modules" ]; then
        npm run build
    else
        print_warning "node_modules not found, skipping build"
    fi
    print_success "Assets built"
fi

# 9. Set permissions
print_info "Setting permissions..."
chmod -R 755 storage bootstrap/cache
if [ "$EUID" -eq 0 ]; then
    chown -R www-data:www-data storage bootstrap/cache
    print_success "Permissions set"
else
    print_warning "Not running as root, run 'sudo chown -R www-data:www-data storage bootstrap/cache' manually"
fi

# 10. Restart services
print_info "Restarting services..."
if [ "$EUID" -eq 0 ]; then
    systemctl restart php8.2-fpm 2>/dev/null || print_warning "Could not restart PHP-FPM"
    systemctl restart nginx 2>/dev/null || systemctl restart apache2 2>/dev/null || print_warning "Could not restart web server"
    print_success "Services restarted"
else
    print_warning "Not running as root, restart services manually:"
    echo "  sudo systemctl restart php8.2-fpm"
    echo "  sudo systemctl restart nginx"
fi

# 11. Disable maintenance mode
print_info "Disabling maintenance mode..."
php artisan up
print_success "Application is now live!"

# 12. Run health checks
print_info "Running health checks..."
echo ""

# Check if application is accessible
if command -v curl &> /dev/null; then
    APP_URL=$(grep APP_URL .env | cut -d '=' -f2)
    HTTP_CODE=$(curl -o /dev/null -s -w "%{http_code}" "$APP_URL" || echo "000")

    if [ "$HTTP_CODE" == "200" ]; then
        print_success "Application is accessible (HTTP $HTTP_CODE)"
    else
        print_error "Application returned HTTP $HTTP_CODE"
    fi
else
    print_warning "curl not found, skipping health check"
fi

# Check database connection
php artisan tinker --execute="DB::connection()->getPdo(); echo 'Database connected';" 2>/dev/null && print_success "Database connection OK" || print_error "Database connection failed"

# Final summary
echo ""
echo "======================================"
echo "Deployment Complete!"
echo "======================================"
echo ""
print_success "Application deployed successfully"
echo ""
echo "Post-deployment tasks:"
echo "  - Monitor logs: tail -f storage/logs/laravel.log"
echo "  - Check application: $APP_URL"
echo "  - Monitor database: mysql -u root -p"
echo "  - Check queue workers: php artisan queue:work"
echo ""
echo "For issues, check:"
echo "  - storage/logs/laravel.log"
echo "  - /var/log/nginx/error.log (or Apache logs)"
echo "  - /var/log/mysql/error.log"
echo ""
