#!/bin/bash

# Exit on error
set -e

# Source environment variables
if [ -f ".env" ]; then
    source .env
else
    echo "Error: .env file not found. Please create it with the required variables."
    exit 1
fi

echo "===== Fixing Certificate Reports Critical Error ====="

# Create script to fix certificate reports
FIX_CERT_SCRIPT="<?php
require_once('wp-load.php');

echo \"Fixing certificate reports critical error...\n\";

// Check the certificate reports template
\$cert_template_path = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/certificates/template-certificate-reports.php';

if (file_exists(\$cert_template_path)) {
    echo \"Found certificate reports template\n\";
    
    // Read the template content
    \$content = file_get_contents(\$cert_template_path);
    
    // Check for common issues that cause critical errors
    \$issues_found = array();
    
    // Check for debug statements
    if (strpos(\$content, 'var_dump') !== false || strpos(\$content, 'print_r') !== false) {
        \$issues_found[] = 'debug statements';
        \$content = preg_replace('/(var_dump|print_r)\\s*\\([^;]*\\);/', '', \$content);
    }
    
    // Check for undefined variables or function calls
    if (strpos(\$content, 'undefined') !== false) {
        \$issues_found[] = 'undefined references';
    }
    
    // Check for syntax errors with escaped characters
    if (strpos(\$content, '\\\\!==') !== false || strpos(\$content, '\\\\!=') !== false) {
        \$issues_found[] = 'escaped operators';
        \$content = str_replace(array('\\\\!==', '\\\\!=', '\\\\!'), array('!==', '!=', '!'), \$content);
    }
    
    if (!empty(\$issues_found)) {
        echo \"Found issues: \" . implode(', ', \$issues_found) . \"\n\";
        
        // Create a backup
        file_put_contents(\$cert_template_path . '.backup', \$content);
        
        // Save the fixed content
        if (file_put_contents(\$cert_template_path, \$content)) {
            echo \"Fixed certificate reports template\n\";
        } else {
            echo \"Failed to fix certificate reports template\n\";
        }
    } else {
        echo \"No obvious issues found in template\n\";
        
        // Create a minimal working template as fallback
        \$minimal_template = '<?php
/**
 * Certificate Reports Template
 */

if ( ! defined( \"ABSPATH\" ) ) {
    exit;
}

// Check if user is logged in and has permission
if ( ! is_user_logged_in() ) {
    echo \"<p>Please log in to view certificate reports.</p>\";
    return;
}

if ( ! current_user_can( \"view_hvac_dashboard\" ) ) {
    echo \"<p>You do not have permission to view certificate reports.</p>\";
    return;
}

?>
<div class=\"hvac-certificate-reports\">
    <h2>Certificate Reports</h2>
    <p>Certificate reporting functionality is being restored.</p>
    <p>This page will show certificate generation and management tools once the system is fully operational.</p>
    
    <div class=\"hvac-certificate-placeholder\">
        <h3>Coming Soon</h3>
        <ul>
            <li>Certificate generation reports</li>
            <li>Attendee certificate status</li>
            <li>Bulk certificate operations</li>
            <li>Certificate download management</li>
        </ul>
    </div>
</div>';
        
        // Save the minimal template
        if (file_put_contents(\$cert_template_path, \$minimal_template)) {
            echo \"Created minimal certificate reports template\n\";
        } else {
            echo \"Failed to create minimal template\n\";
        }
    }
} else {
    echo \"Certificate reports template not found\n\";
    
    // Create the template directory if it doesn't exist
    \$cert_dir = WP_CONTENT_DIR . '/plugins/hvac-community-events/templates/certificates';
    if (!is_dir(\$cert_dir)) {
        mkdir(\$cert_dir, 0755, true);
        echo \"Created certificates template directory\n\";
    }
    
    // Create a basic template
    \$basic_template = '<?php
/**
 * Certificate Reports Template
 */

if ( ! defined( \"ABSPATH\" ) ) {
    exit;
}

if ( ! is_user_logged_in() ) {
    echo \"<p>Please log in to view certificate reports.</p>\";
    return;
}

?>
<div class=\"hvac-certificate-reports\">
    <h2>Certificate Reports</h2>
    <p>Certificate reports are currently being set up.</p>
</div>';
    
    if (file_put_contents(\$cert_template_path, \$basic_template)) {
        echo \"Created basic certificate reports template\n\";
    } else {
        echo \"Failed to create basic template\n\";
    }
}

echo \"Certificate reports fix complete\n\";
"

# Execute the fix
echo "Executing certificate reports fix..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && cat > fix-cert-reports.php << 'EOF'
$FIX_CERT_SCRIPT
EOF"

sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && php fix-cert-reports.php"

# Clean up
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no "$UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP" "cd $UPSKILL_STAGING_PATH && rm fix-cert-reports.php"

echo -e "\n===== Certificate Reports Fix Complete ====="
echo "The certificate reports page should now load without critical errors."
echo "Please try accessing the Certificate Reports page again."