#!/bin/bash

# Fix Apache DocumentRoot Issue for Socialvibe
# This script creates .htaccess files to redirect root traffic to public/ folder
# Run this from the server: bash fix_apache_redirect.sh

echo "🔧 Starting Apache redirect fix..."

cd /home/tcinovas/socialvibe.asia

# Pastikan .htaccess di public/ folder ada
echo "📝 Creating .htaccess in public/ folder..."
cat > public/.htaccess << 'EOF'
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
EOF
echo "✅ public/.htaccess created"

# Buat .htaccess di root folder untuk redirect ke public
echo "📝 Creating .htaccess in root folder..."
cat > .htaccess << 'EOF'
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
EOF
echo "✅ root .htaccess created"

# Clear caches
echo "🧹 Clearing Laravel caches..."
php artisan optimize:clear
echo "✅ optimize:clear done"

php artisan config:cache
echo "✅ config:cache done"

php artisan optimize
echo "✅ optimize done"

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

echo ""
echo "✅ All done!"
echo ""
echo "📋 Next steps:"
echo "1. Contact Domainesia support to update DocumentRoot to: /home/tcinovas/socialvibe.asia/public"
echo "2. Or if you have SSH access, run:"
echo "   sudo nano /etc/apache2/sites-enabled/socialvibe.asia.conf"
echo "   Change: DocumentRoot /home/tcinovas/socialvibe.asia"
echo "   To: DocumentRoot /home/tcinovas/socialvibe.asia/public"
echo "3. Then restart Apache: sudo systemctl restart apache2"
echo ""
echo "🚀 After fix is applied, visit: https://socialvibe.asia"
