#!/bin/bash

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

echo -e "${BLUE}========================================${NC}"
echo -e "${YELLOW}    Clinic Laravel Deployment${NC}"
echo -e "${BLUE}========================================${NC}"
echo "Timestamp: $(date)"
echo ""

# Configuration
PROJECT_DIR="/volume1/Web/clinic"
BRANCH="main"
ENV_FILE="$PROJECT_DIR/.env"
LOG_FILE="$PROJECT_DIR/storage/logs/deploy.log"
BACKUP_DIR="$PROJECT_DIR/storage/backups"

# Create log directory
mkdir -p "$(dirname "$LOG_FILE")"
mkdir -p "$BACKUP_DIR"

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
    echo "$1"
}

# Error function
error() {
    echo -e "${RED}$1${NC}"
    log "ERROR: $1"
    exit 1
}

# Success function
success() {
    echo -e "${GREEN}$1${NC}"
    log "SUCCESS: $1"
}

# Change to project directory
cd "$PROJECT_DIR" || error "Cannot change to $PROJECT_DIR"

log "=== Deployment started ==="
echo -e "${YELLOW}Step 1: Pulling latest code...${NC}"

# Pull latest changes
if git pull origin "$BRANCH"; then
    success "✓ Git pull successful"
else
    error "✗ Git pull failed"
fi

echo -e "${YELLOW}Step 2: Installing PHP dependencies...${NC}"

# Install Composer dependencies
if [ -f "composer.json" ]; then
    if composer install --no-dev --optimize-autoloader --no-interaction; then
        success "✓ Composer dependencies installed"
    else
        error "✗ Composer install failed"
    fi
fi

echo -e "${YELLOW}Step 3: Installing Node.js dependencies...${NC}"

# Install Node.js dependencies
if [ -f "package.json" ]; then
    if npm ci --only=production; then
        success "✓ Node.js dependencies installed"
    else
        error "✗ npm install failed"
    fi
fi

echo -e "${YELLOW}Step 4: Building assets...${NC}"

# Build assets
if [ -f "vite.config.js" ] || [ -f "webpack.mix.js" ]; then
    if npm run build; then
        success "✓ Assets built successfully"
    else
        error "✗ Asset build failed"
    fi
fi

echo -e "${YELLOW}Step 5: Running Laravel maintenance...${NC}"

# Only run migrations and cache clear if .env exists
if [ -f "$ENV_FILE" ]; then
    # Cache clear
    php artisan config:clear
    php artisan cache:clear
    php artisan view:clear
    success "✓ Cache cleared"
    
    # Run migrations (optional - remove if you don't want auto-migrations)
    # php artisan migrate --force
    # success "✓ Database migrations completed"
else
    echo -e "${YELLOW}⚠ .env file not found, skipping Laravel maintenance${NC}"
fi

echo -e "${YELLOW}Step 6: Setting permissions...${NC}"

# Set proper permissions
chmod -R 755 storage bootstrap/cache
chmod -R 775 storage
chown -R admin:administrators storage bootstrap/cache
success "✓ Permissions set"

echo -e "${YELLOW}Step 7: Creating backup...${NC}"

# Create a backup of current state
BACKUP_FILE="$BACKUP_DIR/backup-$(date +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$BACKUP_FILE" . --exclude=".git" --exclude="node_modules" --exclude="vendor" 2>/dev/null
if [ $? -eq 0 ]; then
    success "✓ Backup created: $(basename "$BACKUP_FILE")"
else
    echo -e "${YELLOW}⚠ Backup creation skipped${NC}"
fi

# Clean old backups (keep last 5)
cd "$BACKUP_DIR" && ls -t *.tar.gz | tail -n +6 | xargs -r rm -f

log "=== Deployment completed successfully ==="
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}✅ Deployment completed successfully!${NC}"
echo -e "${BLUE}========================================${NC}"
