#!/bin/bash
set -e

# Fix Apache/Laravel DocumentRoot for pay.tcinovasi.com
# Run from: /home/tcinovas/pay.tcinovasi.com
#
# PREFERRED:
#   DocumentRoot = /home/tcinovas/pay.tcinovasi.com/public
#
# FALLBACK:
#   If the hosting panel cannot change DocumentRoot, the root .htaccess
#   internally rewrites requests to public/ without redirecting the browser.

echo "Starting Laravel Apache configuration fix..."

cd /home/tcinovas/pay.tcinovasi.com

if [ ! -f "public/index.php" ]; then
    echo "ERROR: public/index.php not found."
    exit 1
fi

echo "Writing public/.htaccess..."
cat > public/.htaccess <<'EOF'
<IfModule mod_rewrite.c>
    RewriteEngine On

    # Preserve Authorization header for API requests.
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    # Remove trailing slash from non-directories.
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Laravel front controller.
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
EOF

echo "Writing root .htaccess fallback..."
cat > .htaccess <<'EOF'
<IfModule mod_rewrite.c>
    RewriteEngine On

    # Leave real files/directories alone.
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # IMPORTANT: internal rewrite only; never redirect to /public.
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
EOF

echo "Clearing Laravel caches..."
php artisan optimize:clear

echo "Rebuilding config cache..."
php artisan config:cache

echo "Setting permissions..."
chmod 755 .
chmod 755 public
chmod 644 .htaccess
chmod 644 public/.htaccess
chmod -R 775 storage bootstrap/cache

echo
echo "DONE."
echo
echo "Preferred hosting setting:"
echo "  DocumentRoot = /home/tcinovas/pay.tcinovasi.com/public"
echo
echo "If DocumentRoot cannot be changed, the root .htaccess fallback is active."
echo
echo "Test:"
echo "  curl -i https://pay.tcinovasi.com/api/health"
