#!/bin/bash

# Laravel Deployment Script
# This script clears all caches after uploading files to the server

echo "🚀 Starting Laravel deployment cache clearing..."

# Navigate to project directory
cd "$(dirname "$0")"

# Check if artisan exists
if [ ! -f "artisan" ]; then
    echo "❌ Error: artisan file not found. Make sure you're in the Laravel root directory."
    exit 1
fi

# Clear application cache
echo "📦 Clearing application cache..."
php artisan cache:clear

# Clear configuration cache
echo "⚙️  Clearing configuration cache..."
php artisan config:clear

# Clear route cache
echo "🛣️  Clearing route cache..."
php artisan route:clear

# Clear view cache (compiled Blade templates)
echo "👁️  Clearing view cache..."
php artisan view:clear

# Clear compiled classes
echo "🔧 Clearing compiled classes..."
php artisan clear-compiled

# Optimize autoloader
echo "📚 Optimizing autoloader..."
composer dump-autoload --optimize --no-dev

# Clear OPcache if available
echo "💾 Attempting to clear OPcache..."
php -r "if (function_exists('opcache_reset')) { opcache_reset(); echo 'OPcache cleared successfully\n'; } else { echo 'OPcache not available\n'; }"

# Set proper permissions
echo "🔐 Setting permissions..."
chmod -R 755 storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

echo "✅ Deployment cache clearing completed!"
echo ""
echo "📝 Next steps:"
echo "   1. Clear your browser cache (Ctrl+Shift+Delete or Cmd+Shift+Delete)"
echo "   2. Try accessing the site in incognito/private mode"
echo "   3. If using a CDN, clear CDN cache"
echo "   4. If still seeing old content, restart your web server:"
echo "      - Apache: sudo systemctl restart apache2"
echo "      - Nginx: sudo systemctl restart nginx"

