#!/bin/bash

# 🚀 Panel IRChem Deployment Script
# This script automates the deployment process for production

set -e  # Exit on any error

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

# Configuration - Update these for your server
APP_NAME="Panel IRChem"
APP_DIR="/var/www/panel.irchem.ir"
BACKUP_DIR="/backups"
DB_NAME="crminome"
DB_USER="panel_user"
DB_PASSWORD="your_secure_password_here"

# Functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   log_error "This script should not be run as root for security reasons"
   exit 1
fi

# Check if required commands exist
check_requirements() {
    log_info "Checking requirements..."
    
    if ! command -v php &> /dev/null; then
        log_error "PHP is not installed"
        exit 1
    fi
    
    if ! command -v composer &> /dev/null; then
        log_error "Composer is not installed"
        exit 1
    fi
    
    if ! command -v npm &> /dev/null; then
        log_error "NPM is not installed"
        exit 1
    fi
    
    if ! command -v mysql &> /dev/null; then
        log_error "MySQL is not installed"
        exit 1
    fi
    
    log_success "All requirements are met"
}

# Backup current database
backup_database() {
    log_info "Creating database backup..."
    
    if [ ! -d "$BACKUP_DIR" ]; then
        sudo mkdir -p "$BACKUP_DIR"
        sudo chown $USER:$USER "$BACKUP_DIR"
    fi
    
    DATE=$(date +%Y%m%d_%H%M%S)
    BACKUP_FILE="$BACKUP_DIR/panel_backup_$DATE.sql"
    
    mysqldump -u $DB_USER -p$DB_PASSWORD $DB_NAME > "$BACKUP_FILE"
    
    if [ $? -eq 0 ]; then
        log_success "Database backup created: $BACKUP_FILE"
    else
        log_error "Database backup failed"
        exit 1
    fi
}

# Update application code
update_code() {
    log_info "Updating application code..."
    
    cd "$APP_DIR"
    
    # Pull latest changes
    git pull origin main
    
    if [ $? -eq 0 ]; then
        log_success "Code updated successfully"
    else
        log_error "Failed to update code"
        exit 1
    fi
}

# Install dependencies
install_dependencies() {
    log_info "Installing dependencies..."
    
    cd "$APP_DIR"
    
    # Install PHP dependencies
    composer install --no-dev --optimize-autoloader --no-interaction
    
    if [ $? -eq 0 ]; then
        log_success "PHP dependencies installed"
    else
        log_error "Failed to install PHP dependencies"
        exit 1
    fi
    
    # Install NPM dependencies
    npm install --production
    
    if [ $? -eq 0 ]; then
        log_success "NPM dependencies installed"
    else
        log_error "Failed to install NPM dependencies"
        exit 1
    fi
}

# Build assets
build_assets() {
    log_info "Building assets..."
    
    cd "$APP_DIR"
    
    npm run build
    
    if [ $? -eq 0 ]; then
        log_success "Assets built successfully"
    else
        log_error "Failed to build assets"
        exit 1
    fi
}

# Run migrations
run_migrations() {
    log_info "Running database migrations..."
    
    cd "$APP_DIR"
    
    php artisan migrate --force
    
    if [ $? -eq 0 ]; then
        log_success "Migrations completed successfully"
    else
        log_error "Migrations failed"
        exit 1
    fi
}

# Clear caches
clear_caches() {
    log_info "Clearing caches..."
    
    cd "$APP_DIR"
    
    php artisan cache:clear
    php artisan config:clear
    php artisan route:clear
    php artisan view:clear
    
    log_success "Caches cleared"
}

# Optimize for production
optimize_production() {
    log_info "Optimizing for production..."
    
    cd "$APP_DIR"
    
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    
    log_success "Application optimized for production"
}

# Set permissions
set_permissions() {
    log_info "Setting file permissions..."
    
    cd "$APP_DIR"
    
    # Set ownership
    sudo chown -R www-data:www-data "$APP_DIR"
    
    # Set directory permissions
    sudo find "$APP_DIR" -type d -exec chmod 755 {} \;
    
    # Set file permissions
    sudo find "$APP_DIR" -type f -exec chmod 644 {} \;
    
    # Set writable directories
    sudo chmod -R 775 "$APP_DIR/storage"
    sudo chmod -R 775 "$APP_DIR/bootstrap/cache"
    
    log_success "Permissions set correctly"
}

# Test application
test_application() {
    log_info "Testing application..."
    
    cd "$APP_DIR"
    
    # Test database connection
    php artisan tinker --execute="DB::connection()->getPdo(); echo 'Database connection: OK';"
    
    if [ $? -eq 0 ]; then
        log_success "Database connection test passed"
    else
        log_error "Database connection test failed"
        exit 1
    fi
    
    # Test route cache
    php artisan route:list > /dev/null
    
    if [ $? -eq 0 ]; then
        log_success "Route cache test passed"
    else
        log_error "Route cache test failed"
        exit 1
    fi
}

# Restart services
restart_services() {
    log_info "Restarting services..."
    
    # Restart PHP-FPM
    sudo systemctl restart php8.1-fpm
    
    # Restart Nginx
    sudo systemctl restart nginx
    
    log_success "Services restarted"
}

# Main deployment function
main() {
    log_info "Starting deployment of $APP_NAME..."
    
    check_requirements
    backup_database
    update_code
    install_dependencies
    build_assets
    run_migrations
    clear_caches
    optimize_production
    set_permissions
    test_application
    restart_services
    
    log_success "Deployment completed successfully! 🎉"
    log_info "Application is now available at: https://irchembuy.liara.run/"
}

# Run main function
main "$@"