#!/bin/bash

echo "====================================="
echo "Divine Reports - Reports System Setup"
echo "====================================="

# Check if composer is installed
if ! command -v composer &> /dev/null; then
    echo "❌ Composer is not installed. Please install Composer first:"
    echo "   Visit: https://getcomposer.org/download/"
    exit 1
fi

echo "✅ Composer found"

# Install dependencies
echo "📦 Installing dependencies..."
composer install --no-dev --optimize-autoloader

if [ $? -eq 0 ]; then
    echo "✅ Dependencies installed successfully"
else
    echo "❌ Failed to install dependencies"
    exit 1
fi

# Create reports directory
echo "📁 Creating reports directory..."
mkdir -p reports
chmod 755 reports

if [ -d "reports" ]; then
    echo "✅ Reports directory created"
else
    echo "❌ Failed to create reports directory"
    exit 1
fi

# Create vendor directory symlink if needed (for web access)
if [ ! -L "vendor" ] && [ -d "vendor" ]; then
    echo "✅ Vendor directory is ready"
fi

# Check PHP version
PHP_VERSION=$(php -r "echo PHP_VERSION;")
echo "🐘 PHP Version: $PHP_VERSION"

# Check required PHP extensions
echo "🔍 Checking PHP extensions..."

REQUIRED_EXTENSIONS=("zip" "xml" "mbstring" "gd")
MISSING_EXTENSIONS=()

for ext in "${REQUIRED_EXTENSIONS[@]}"; do
    if php -m | grep -q "^$ext$"; then
        echo "  ✅ $ext"
    else
        echo "  ❌ $ext (missing)"
        MISSING_EXTENSIONS+=("$ext")
    fi
done

if [ ${#MISSING_EXTENSIONS[@]} -gt 0 ]; then
    echo ""
    echo "⚠️  Missing PHP extensions. Please install:"
    for ext in "${MISSING_EXTENSIONS[@]}"; do
        echo "   - php-$ext"
    done
    echo ""
    echo "On Ubuntu/Debian: sudo apt install php-${MISSING_EXTENSIONS[*]}"
    echo "On CentOS/RHEL: sudo yum install php-${MISSING_EXTENSIONS[*]}"
fi

# Test file permissions
echo "🔒 Testing file permissions..."
if [ -w "reports" ]; then
    echo "✅ Reports directory is writable"
else
    echo "❌ Reports directory is not writable"
    echo "   Run: chmod 755 reports"
fi

# Check database connection (if config.php exists)
if [ -f "config.php" ]; then
    echo "🗃️  Database configuration found"
    # Test could be added here to verify DB connection
else
    echo "⚠️  config.php not found - make sure database is configured"
fi

echo ""
echo "====================================="
echo "✅ Setup Complete!"
echo "====================================="
echo ""
echo "Next steps:"
echo "1. Ensure your web server can access the 'reports' directory"
echo "2. Login as admin and navigate to Dashboard > Printouts"
echo "3. Test report generation with a small dataset first"
echo ""
echo "For support, see README_REPORTS.md"
echo ""