#!/bin/bash

echo "🧹 Starting Laravel Cache Clearing Process (Direct Hosting)..."
echo "============================================================="

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

# Function to run commands and check for errors
run_command() {
    local cmd="$1"
    local description="$2"
    
    echo -e "${BLUE}➤ ${description}...${NC}"
    if eval "$cmd"; then
        echo -e "${GREEN}✅ ${description} completed successfully${NC}"
    else
        echo -e "${RED}❌ Failed: ${description}${NC}"
        return 1
    fi
    echo ""
}

# CRITICAL: Regenerate autoloader FIRST (before any Laravel commands)
echo -e "${BLUE}🔄 Regenerating autoloader (CRITICAL for new classes)...${NC}"
run_command "sudo -u www-data composer dump-autoload --optimize --no-dev" "Regenerating optimized autoloader"

# Remove ALL cached files first (before any artisan commands)
echo -e "${YELLOW}🗑️  Removing ALL cached files (including config cache)...${NC}"
run_command "sudo -u www-data rm -f bootstrap/cache/packages.php" "Removing cached packages file"
run_command "sudo -u www-data rm -f bootstrap/cache/config.php" "Removing cached config file"
run_command "sudo -u www-data rm -f bootstrap/cache/services.php" "Removing cached services file"
run_command "sudo -u www-data rm -f bootstrap/cache/routes-v7.php" "Removing cached routes file"
run_command "sudo -u www-data rm -f bootstrap/cache/events.php" "Removing cached events file"

# Rebuild package discovery after removing cached files
run_command "sudo -u www-data php artisan package:discover" "Rebuilding package discovery cache"

# Clear all Laravel caches
run_command "sudo -u www-data php artisan optimize:clear" "Clearing all Laravel caches (routes, config, views, etc.)"

# Individual cache clearing commands for thoroughness
run_command "sudo -u www-data php artisan cache:clear" "Clearing application cache"
run_command "sudo -u www-data php artisan config:clear" "Clearing configuration cache"
run_command "sudo -u www-data php artisan route:clear" "Clearing route cache"
run_command "sudo -u www-data php artisan view:clear" "Clearing compiled view files"
run_command "sudo -u www-data php artisan event:clear" "Clearing cached events"

# Clear OPcache if available
run_command "sudo -u www-data php artisan opcache:clear" "Clearing OPcache (if available)"

# Additional autoloader regeneration (double-ensure)
run_command "sudo -u www-data composer dump-autoload --optimize" "Re-optimizing autoloader after cache clear"

# Rebuild caches for production
echo -e "${YELLOW}🔧 Rebuilding optimized caches for production...${NC}"
run_command "sudo -u www-data php artisan config:cache" "Caching configuration"
run_command "sudo -u www-data php artisan route:cache" "Caching routes"
run_command "sudo -u www-data php artisan view:cache" "Caching views"
run_command "sudo -u www-data php artisan event:cache" "Caching events"

# Clear Redis cache (if using Redis for caching)
echo -e "${YELLOW}🗃️  Clearing Redis cache...${NC}"
run_command "redis-cli FLUSHALL" "Flushing all Redis data"

# Clear Memcached if it exists
echo -e "${YELLOW}🗃️  Clearing Memcached cache (if available)...${NC}"
if command -v memcached &> /dev/null; then
    run_command "echo 'flush_all' | nc localhost 11211" "Flushing all Memcached data"
fi

# Clear Laravel sessions
echo -e "${YELLOW}👥 Clearing user sessions...${NC}"
run_command "sudo -u www-data php artisan session:flush" "Clearing all user sessions"

# Clear Nginx FastCGI cache if it exists
echo -e "${YELLOW}🌐 Clearing Nginx FastCGI cache...${NC}"
if [ -d "/var/cache/nginx" ]; then
    run_command "sudo rm -rf /var/cache/nginx/*" "Clearing Nginx FastCGI cache"
fi

# Clear any temp files and compiled assets
echo -e "${YELLOW}📦 Clearing temporary files and compiled assets...${NC}"
run_command "sudo -u www-data rm -rf storage/framework/cache/data/*" "Clearing framework cache data"
run_command "sudo -u www-data rm -rf storage/framework/sessions/*" "Clearing session files"
run_command "sudo -u www-data rm -rf storage/framework/views/*" "Clearing compiled views"

# Clear storage/logs if needed
echo -e "${YELLOW}📝 Clearing storage logs...${NC}"
run_command "find storage/logs -name '*.log' -type f -delete 2>/dev/null" "Clearing log files"

# Add cache-busting timestamp to prevent browser caching
echo -e "${YELLOW}⚡ Adding cache-busting mechanisms...${NC}"
TIMESTAMP=$(date +%s)
run_command "echo 'CACHE_VERSION=${TIMESTAMP}' >> .env" "Adding cache-busting timestamp"

# Clear PHP internal class cache
echo -e "${YELLOW}🧠 Clearing PHP internal caches...${NC}"
run_command "sudo -u www-data php -r \"if (function_exists('opcache_reset')) opcache_reset();\"" "Resetting PHP OPcache"
run_command "sudo -u www-data php -r \"if (function_exists('apc_clear_cache')) { apc_clear_cache(); apc_clear_cache('user'); }\"" "Clearing APC cache"

# Force restart services to clear all memory caches
echo -e "${YELLOW}🔄 Restarting services to clear memory caches...${NC}"
run_command "sudo systemctl restart php8.3-fpm" "Restarting PHP-FPM"
run_command "sudo systemctl restart nginx" "Restarting Nginx"
run_command "sudo systemctl restart redis-server" "Restarting Redis"

# Set proper permissions
echo -e "${YELLOW}🔐 Setting proper permissions...${NC}"
run_command "sudo chown -R www-data:www-data storage bootstrap/cache" "Setting storage permissions"
run_command "sudo chmod -R 775 storage bootstrap/cache" "Setting storage file permissions"

# Show final status
echo ""
echo -e "${GREEN}🎉 Cache clearing process completed!${NC}"
echo -e "${BLUE}📊 Service Status:${NC}"
systemctl status nginx php8.3-fpm redis-server | grep "Active:"

echo ""
echo -e "${GREEN}✨ Your Laravel application caches have been cleared and optimized!${NC}"
echo -e "${GREEN}🔄 Services have been restarted to ensure all memory caches are cleared.${NC}"
echo ""
echo -e "${BLUE}📋 If users still see cached versions, try these additional steps:${NC}"
echo -e "${YELLOW}   • Hard refresh in browser: ${NC}Ctrl+Shift+R (or Cmd+Shift+R on Mac)"
echo -e "${YELLOW}   • Clear browser data: ${NC}Settings > Privacy > Clear browsing data"
echo -e "${YELLOW}   • Check .env CACHE_VERSION: ${NC}cat .env | grep CACHE_VERSION"
echo -e "${YELLOW}   • Verify services status: ${NC}sudo systemctl status nginx php8.3-fpm redis-server"
echo ""
echo -e "${BLUE}🐛 For persistent issues, check:${NC}"
echo -e "${YELLOW}   • Browser console for 304 responses${NC}"
echo -e "${YELLOW}   • Network tab for cached resources${NC}"
echo -e "${YELLOW}   • nginx access logs: ${NC}sudo tail -f /var/log/nginx/access.log"
echo -e "${YELLOW}   • PHP error logs: ${NC}sudo tail -f /var/log/php8.3-fpm.log"