#!/bin/bash
# Fix HTTP 500 error on billing site
# Run with: sudo bash fix-billing-500.sh

echo "=== Fixing HTTP 500 Error on Billing Site ==="
echo ""

# Check for duplicate ionCube entries
echo "1. Checking for duplicate ionCube configurations..."
DUPLICATES=$(grep -i "zend_extension.*ioncube" /etc/php/8.3/fpm/php.ini /etc/php/8.3/fpm/conf.d/*.ini 2>/dev/null | wc -l)
echo "   Found $DUPLICATES ionCube configuration entries"

if [ "$DUPLICATES" -gt 1 ]; then
    echo "⚠️  Multiple ionCube entries found - this can cause conflicts"
    echo "   Removing from main php.ini, keeping only conf.d entry..."
    sudo sed -i '/zend_extension.*ioncube/d' /etc/php/8.3/fpm/php.ini
    echo "✓ Removed duplicate from php.ini"
fi

echo ""

# Verify configuration
echo "2. Verifying ionCube configuration..."
CONFIG_FILE="/etc/php/8.3/fpm/conf.d/00-ioncube.ini"
if [ -f "$CONFIG_FILE" ]; then
    echo "   Config file: $CONFIG_FILE"
    cat "$CONFIG_FILE"
else
    echo "   ❌ Config file not found!"
    exit 1
fi

echo ""

# Check if loader file exists
LOADER_FILE="/usr/lib/php/20230831/ioncube_loader_lin_8.3.so"
if [ ! -f "$LOADER_FILE" ]; then
    echo "❌ Loader file not found: $LOADER_FILE"
    exit 1
fi
echo "✓ Loader file exists"

echo ""

# Test PHP syntax
echo "3. Testing PHP configuration..."
if php8.3 -c /etc/php/8.3/fpm/php.ini -r "echo 'OK';" 2>&1 | grep -q "OK"; then
    echo "✓ PHP configuration is valid"
else
    echo "❌ PHP configuration has errors"
    php8.3 -c /etc/php/8.3/fpm/php.ini -r "echo 'OK';" 2>&1
    exit 1
fi

echo ""

# Restart PHP-FPM
echo "4. Restarting PHP-FPM 8.3..."
sudo systemctl restart php8.3-fpm
sleep 3

if sudo systemctl is-active --quiet php8.3-fpm; then
    echo "✓ PHP-FPM 8.3 restarted"
else
    echo "❌ PHP-FPM 8.3 failed to restart"
    sudo systemctl status php8.3-fpm --no-pager | head -10
    exit 1
fi

echo ""

# Check PHP-FPM error log
echo "5. Checking PHP-FPM error log..."
if [ -f /var/log/php8.3-fpm.log ]; then
    ERRORS=$(sudo tail -5 /var/log/php8.3-fpm.log | grep -i error | wc -l)
    if [ "$ERRORS" -gt 0 ]; then
        echo "⚠️  Found errors in PHP-FPM log:"
        sudo tail -5 /var/log/php8.3-fpm.log | grep -i error
    else
        echo "✓ No recent errors in PHP-FPM log"
    fi
fi

echo ""

# Test billing site
echo "6. Testing billing site..."
sleep 2
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://billing.friendlytv.site/ 2>&1)
echo "   HTTP Status: $HTTP_CODE"

if [ "$HTTP_CODE" = "200" ]; then
    echo ""
    echo "✅ SUCCESS! Billing site is working!"
elif [ "$HTTP_CODE" = "500" ]; then
    echo ""
    echo "⚠️  Still getting 500 error"
    echo ""
    echo "Check Apache error log:"
    echo "   sudo tail -20 /var/log/apache2/error.log | grep billing"
    echo ""
    echo "Check PHP-FPM log:"
    echo "   sudo tail -20 /var/log/php8.3-fpm.log"
else
    echo ""
    echo "⚠️  Getting HTTP $HTTP_CODE"
fi

