#!/bin/bash

# DIVINE REPORTS - Enhanced PDF Generation Installation Script
# This script helps install and configure the enhanced PDF generation features

echo "=========================================="
echo "DIVINE REPORTS - PDF Enhancement Setup"
echo "=========================================="
echo

# Check if we're in the right directory
if [ ! -f "admin_exam_grade_reports.php" ]; then
    echo "❌ Error: admin_exam_grade_reports.php not found in current directory"
    echo "Please run this script from your DIVINE REPORTS project root directory"
    exit 1
fi

echo "✅ Found admin_exam_grade_reports.php"
echo

# Check PHP version
PHP_VERSION=$(php -v | head -n1 | cut -d " " -f 2 | cut -d "." -f 1,2)
REQUIRED_VERSION="7.4"

if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$PHP_VERSION" | sort -V | head -n1)" = "$REQUIRED_VERSION" ]; then 
    echo "✅ PHP Version: $PHP_VERSION (meets minimum requirement of $REQUIRED_VERSION)"
else
    echo "❌ PHP Version: $PHP_VERSION (requires minimum $REQUIRED_VERSION)"
    exit 1
fi
echo

# Check if composer is available
if command -v composer &> /dev/null; then
    echo "✅ Composer found"
    HAS_COMPOSER=true
else
    echo "⚠️  Composer not found - will use manual installation"
    HAS_COMPOSER=false
fi
echo

# Install dependencies
echo "📦 Installing PDF generation dependencies..."
echo

if [ "$HAS_COMPOSER" = true ]; then
    # Install via Composer
    echo "Installing dompdf..."
    composer require dompdf/dompdf --no-interaction
    
    echo "Installing QR code library..."
    composer require endroid/qr-code --no-interaction
    
    echo "Installing image processing library..."
    composer require intervention/image --no-interaction
    
else
    # Manual installation
    echo "Manual installation required:"
    echo "1. Download dompdf from: https://github.com/dompdf/dompdf/releases"
    echo "2. Extract to: vendor/dompdf/dompdf/"
    echo "3. Download endroid/qr-code from: https://github.com/endroid/qr-code/releases"
    echo "4. Extract to: vendor/endroid/qr-code/"
    echo "5. Download intervention/image from: https://github.com/Intervention/image/releases"
    echo "6. Extract to: vendor/intervention/image/"
    echo
    echo "Press Enter after completing manual installation..."
    read -p ""
fi

# Create necessary directories
echo "📁 Creating necessary directories..."
mkdir -p vendor/autoload
mkdir -p uploads/pdfs
mkdir -p uploads/qrcodes
echo "✅ Directories created"
echo

# Set proper permissions
echo "🔒 Setting file permissions..."
chmod 755 vendor/
chmod 755 uploads/
chmod 755 uploads/pdfs/
chmod 755 uploads/qrcodes/
echo "✅ Permissions set"
echo

# Backup existing file
echo "💾 Creating backup of admin_exam_grade_reports.php..."
cp admin_exam_grade_reports.php admin_exam_grade_reports.php.backup.$(date +%Y%m%d_%H%M%S)
echo "✅ Backup created"
echo

# Check if pdf_enhancement_solution.php exists
if [ ! -f "pdf_enhancement_solution.php" ]; then
    echo "❌ pdf_enhancement_solution.php not found"
    echo "Please ensure the enhancement solution file is in the current directory"
    exit 1
fi

echo "✅ Enhancement solution file found"
echo

# Test PDF generation
echo "🧪 Testing PDF generation capabilities..."
php -r "
require_once 'vendor/autoload.php';
if (class_exists('Dompdf\\Dompdf')) {
    echo '✅ dompdf is properly installed and accessible\n';
} else {
    echo '❌ dompdf installation issue detected\n';
    exit(1);
}
if (class_exists('Endroid\\QrCode\\QrCode')) {
    echo '✅ QR code library is properly installed\n';
} else {
    echo '⚠️  QR code library not detected (optional)\n';
}
if (class_exists('Intervention\\Image\\ImageManager')) {
    echo '✅ Image processing library is properly installed\n';
} else {
    echo '⚠️  Image processing library not detected (optional)\n';
}
"

if [ $? -eq 0 ]; then
    echo "✅ PDF generation dependencies are properly configured"
else
    echo "❌ Some dependencies have issues"
    echo "Please check the installation and try again"
    exit 1
fi
echo

# Check PHP configuration
echo "⚙️  Checking PHP configuration..."
PHP_MEMORY_LIMIT=$(php -r "echo ini_get('memory_limit');")
echo "Current memory limit: $PHP_MEMORY_LIMIT"

# Offer to increase memory limit for better performance
if [[ "$PHP_MEMORY_LIMIT" == "128M" ]] || [[ "$PHP_MEMORY_LIMIT" == "256M" ]]; then
    echo "⚠️  Memory limit is relatively low for PDF generation"
    read -p "Would you like to create a .htaccess file to increase memory limit to 512M? (y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "# Increase memory limit for PDF generation" > .htaccess
        echo "php_value memory_limit 512M" >> .htaccess
        echo "php_value max_execution_time 300" >> .htaccess
        echo "✅ .htaccess created with increased limits"
    fi
fi
echo

# Create configuration file
echo "⚙️  Creating PDF generation configuration..."
cat > pdf_config.php << 'EOF'
<?php
/**
 * DIVINE REPORTS - PDF Generation Configuration
 * This file contains configuration settings for PDF generation
 */

return [
    // PDF Settings
    'pdf' => [
        'default_paper_size' => 'A4',
        'default_orientation' => 'portrait',
        'dpi' => 300,
        'font_family' => 'DejaVu Sans',
        'margin_top' => 15,
        'margin_bottom' => 15,
        'margin_left' => 15,
        'margin_right' => 15,
    ],
    
    // Memory and Performance
    'performance' => [
        'memory_limit' => '512M',
        'execution_time' => 300,
        'max_students_per_batch' => 50,
        'enable_caching' => true,
        'cache_duration' => 3600, // 1 hour
    ],
    
    // Security Settings
    'security' => [
        'require_authentication' => true,
        'session_timeout' => 3600,
        'rate_limit_per_hour' => 100,
        'allowed_file_types' => ['pdf', 'jpg', 'jpeg', 'png', 'gif'],
    ],
    
    // Storage Settings
    'storage' => [
        'pdf_directory' => 'uploads/pdfs/',
        'qrcode_directory' => 'uploads/qrcodes/',
        'temp_directory' => sys_get_temp_dir(),
        'cleanup_old_files' => true,
        'cleanup_after_days' => 7,
    ],
    
    // Email Settings (for sending reports)
    'email' => [
        'enabled' => false,
        'smtp_host' => '',
        'smtp_port' => 587,
        'smtp_username' => '',
        'smtp_password' => '',
        'from_email' => '',
        'from_name' => 'DIVINE REPORTS',
    ],
    
    // Debug Settings
    'debug' => [
        'enabled' => false,
        'log_file' => 'logs/pdf_generation.log',
        'show_errors' => false,
        'verbose_logging' => true,
    ]
];
EOF

echo "✅ Configuration file created: pdf_config.php"
echo

# Create logs directory
mkdir -p logs
touch logs/pdf_generation.log
chmod 644 logs/pdf_generation.log
echo "✅ Logs directory created"
echo

# Test database connection
echo "🗄️  Testing database connection..."
php -r "
\$config = require 'config.php';
try {
    \$conn = new mysqli(\$config['DB_SERVER'] ?? 'localhost', \$config['DB_USERNAME'] ?? 'root', \$config['DB_PASSWORD'] ?? '', \$config['DB_NAME'] ?? 'divine_reports');
    if (\$conn->connect_error) {
        throw new Exception('Connection failed: ' . \$conn->connect_error);
    }
    echo '✅ Database connection successful\n';
    \$conn->close();
} catch (Exception \$e) {
    echo '❌ Database connection failed: ' . \$e->getMessage() . '\n';
    exit(1);
}
"

if [ $? -ne 0 ]; then
    echo "❌ Database connection test failed"
    echo "Please check your config.php file and database settings"
    exit 1
fi
echo

# Final installation summary
echo "=========================================="
echo "🎉 INSTALLATION COMPLETE!"
echo "=========================================="
echo
echo "Summary of what was installed:"
echo "✅ PDF generation libraries (dompdf)"
echo "✅ QR code generation support"
echo "✅ Image processing capabilities"
echo "✅ Configuration files"
echo "✅ Directory structure"
echo "✅ Permission settings"
echo
echo "Next steps:"
echo "1. Review and customize pdf_config.php if needed"
echo "2. Test the PDF generation by visiting:"
echo "   admin_exam_grade_reports.php?test_pdf=1"
echo "3. Configure any additional settings as needed"
echo
echo "Files created/modified:"
echo "- admin_exam_grade_reports.php.backup.* (backup)"
echo "- pdf_config.php (new configuration)"
echo "- .htaccess (if memory limit was increased)"
echo
echo "Troubleshooting:"
echo "- Check logs/pdf_generation.log for errors"
echo "- Ensure proper file permissions are set"
echo "- Verify PHP extensions are installed"
echo
echo "For support, refer to the implementation_guide.md file"
echo "=========================================="

# Offer to run a quick test
read -p "Would you like to run a quick PDF generation test now? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "🧪 Running PDF generation test..."
    php -r "
    require_once 'vendor/autoload.php';
    require_once 'pdf_enhancement_solution.php';
    
    echo 'Testing dompdf initialization...' . PHP_EOL;
    try {
        \$dompdf = new Dompdf\Dompdf();
        echo '✅ dompdf initialization successful' . PHP_EOL;
        
        // Test basic PDF generation
        \$html = '<html><body><h1>Test Report</h1><p>This is a test PDF generation.</p></body></html>';
        \$dompdf->loadHtml(\$html);
        \$dompdf->setPaper('A4', 'portrait');
        \$dompdf->render();
        
        \$output = \$dompdf->output();
        if (!empty(\$output)) {
            echo '✅ PDF generation test successful' . PHP_EOL;
            echo '📊 Generated PDF size: ' . strlen(\$output) . ' bytes' . PHP_EOL;
        } else {
            echo '❌ PDF generation returned empty output' . PHP_EOL;
        }
    } catch (Exception \$e) {
        echo '❌ PDF generation test failed: ' . \$e->getMessage() . PHP_EOL;
    }
    "
fi

echo
echo "🎯 Installation script completed!"
echo "=========================================="