#!/bin/bash

echo "=========================================="
echo "  Laravel Server Quick Fix"
echo "=========================================="
echo ""

# Set proper permissions
echo "1. Setting proper permissions..."
chmod -R 775 storage bootstrap/cache
chown -R apache:apache storage bootstrap/cache 2>/dev/null || chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || chown -R nginx:nginx storage bootstrap/cache 2>/dev/null

echo "✓ Permissions set"
echo ""

# Clear all caches
echo "2. Clearing all caches..."
php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear

echo "✓ Caches cleared"
echo ""

# Generate app key if not set
echo "3. Checking application key..."
if grep -q "APP_KEY=$" .env || grep -q "APP_KEY=\"\"" .env; then
    echo "Generating new application key..."
    php artisan key:generate
    echo "✓ Application key generated"
else
    echo "✓ Application key already set"
fi

echo ""

# Create storage link
echo "4. Creating storage link..."
php artisan storage:link
echo "✓ Storage link created"

echo ""

# Check database connection
echo "5. Testing database connection..."
php artisan tinker --execute="try { DB::connection()->getPdo(); echo 'Database connected successfully'; } catch (Exception \$e) { echo 'Database connection failed: ' . \$e->getMessage(); }"

echo ""
echo ""

# Optimize for production
echo "6. Optimizing for production..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "✓ Optimization complete"
echo ""

echo "=========================================="
echo "  ✓ All fixes applied!"
echo "=========================================="
echo ""
echo "Now try accessing your application again."
echo "If still showing blank page, check:"
echo "  - storage/logs/laravel.log"
echo "  - /var/log/httpd/error_log"
echo ""
