$plugin_dir,
    'Zoho' => $zoho_dir,
    'Admin' => $admin_dir,
    'JavaScript' => $js_dir,
    'CSS' => $css_dir,
    'Logs' => $logs_dir
);
foreach ($dirs as $name => $dir) {
    echo "$name directory: ";
    if (file_exists($dir)) {
        echo "Found at $dir\n";
    } else {
        echo "Not found at $dir. Attempting to create...\n";
        if (mkdir($dir, 0755, true)) {
            echo "Created $name directory successfully.\n";
        } else {
            echo "Failed to create $name directory.\n";
        }
    }
}
// Create logs directory
if (\!file_exists($logs_dir)) {
    if (mkdir($logs_dir, 0755, true)) {
        echo "Created logs directory: $logs_dir\n";
    } else {
        echo "Failed to create logs directory: $logs_dir\n";
    }
}
// Check for zoho-config.php
$zoho_config_file = $zoho_dir . '/zoho-config.php';
echo "\nChecking for zoho-config.php...\n";
if (file_exists($zoho_config_file)) {
    echo "Found at $zoho_config_file\n";
    
    // Backup the file
    $backup_file = $zoho_config_file . '.bak.' . date('YmdHis');
    if (copy($zoho_config_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of zoho-config.php\n";
    }
} else {
    echo "Not found at $zoho_config_file. Will create a new one.\n";
}
// Create or update zoho-config.php
echo "\nUpdating zoho-config.php...\n";
$zoho_config_content = <<<'EOT'
get_modules();
        
        // Enhanced error handling and detailed response
        if (\$response && \!isset(\$response['error'])) {
            wp_send_json_success(array(
                'message' => 'Connection successful\!',
                'modules' => isset(\$response['modules']) ? count(\$response['modules']) . ' modules available' : 'No modules found'
            ));
        } else {
            \$error_message = isset(\$response['error']) ? \$response['error'] : 'Unknown error';
            \$error_code = isset(\$response['code']) ? \$response['code'] : '';
            \$error_details = isset(\$response['details']) ? \$response['details'] : '';
            
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] Connection test failed: \$error_message\\n\";
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Error code: \$error_code\\n\";
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Details: \$error_details\\n\";
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Raw response: \" . json_encode(\$response) . \"\\n\";
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log(\$log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            // Send detailed error data back to frontend
            wp_send_json_error(array(
                'message' => 'Connection failed',
                'error' => \$error_message,
                'code' => \$error_code,
                'details' => \$error_details,
                'raw' => json_encode(\$response)
            ));
        }
    }";
        
        // Replace in the file
        $admin_content = preg_replace($pattern, $replacement, $admin_content);
        
        // Save the updated file
        if (file_put_contents($zoho_admin_file, $admin_content)) {
            echo "Updated class-zoho-admin.php successfully.\n";
        } else {
            echo "Failed to update class-zoho-admin.php.\n";
        }
    } else {
        echo "class-zoho-admin.php already patched.\n";
    }
} else {
    echo "Not found at $zoho_admin_file. Creating a new file...\n";
    
    // Create new class-zoho-admin.php
    $admin_content = <<<'EOT'
 admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_zoho_admin_nonce'),
            'testing_connection' => __('Testing connection...', 'hvac-community-events'),
            'connection_success' => __('Connection successful\!', 'hvac-community-events'),
            'connection_error' => __('Connection failed', 'hvac-community-events')
        ));
    }
    /**
     * Render admin page
     */
    public function render_admin_page() {
        ?>
        
            
            
            
                
             
            
            
            
            
            
            get_client_id();
            $client_secret = $zoho_auth->get_client_secret();
            $refresh_token = $zoho_auth->get_refresh_token();
            
            if (empty($client_id) || empty($client_secret) || empty($refresh_token)) {
                echo '
';
                _e('Zoho CRM credentials are not fully configured. Please check your zoho-config.php file and .env file.', 'hvac-community-events');
                echo '
';
                
                if (empty($client_id)) {
                    echo '
ZOHO_CLIENT_ID is missing or empty.
';
                }
                
                if (empty($client_secret)) {
                    echo '
ZOHO_CLIENT_SECRET is missing or empty.
';
                }
                
                if (empty($refresh_token)) {
                    echo '
ZOHO_REFRESH_TOKEN is missing or empty.
';
                }
                
                echo '
';
            } else {
                echo '
';
                _e('Zoho CRM credentials are configured.', 'hvac-community-events');
                echo '
';
            }
            ?>
        
 
        get_modules();
        
        // Enhanced error handling and detailed response
        if ($response && \!isset($response['error'])) {
            wp_send_json_success(array(
                'message' => 'Connection successful\!',
                'modules' => isset($response['modules']) ? count($response['modules']) . ' modules available' : 'No modules found'
            ));
        } else {
            $error_message = isset($response['error']) ? $response['error'] : 'Unknown error';
            $error_code = isset($response['code']) ? $response['code'] : '';
            $error_details = isset($response['details']) ? $response['details'] : '';
            
            // Log the error
            if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
                $log_message = "[" . date('Y-m-d H:i:s') . "] Connection test failed: $error_message\n";
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Error code: $error_code\n";
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Details: $error_details\n";
                $log_message .= "[" . date('Y-m-d H:i:s') . "] Raw response: " . json_encode($response) . "\n";
                
                if (defined('ZOHO_LOG_FILE')) {
                    error_log($log_message, 3, ZOHO_LOG_FILE);
                }
            }
            
            // Send detailed error data back to frontend
            wp_send_json_error(array(
                'message' => 'Connection failed',
                'error' => $error_message,
                'code' => $error_code,
                'details' => $error_details,
                'raw' => json_encode($response)
            ));
        }
    }
}
// Initialize the admin class
new HVAC_Zoho_Admin();
EOT;
    if (file_put_contents($zoho_admin_file, $admin_content)) {
        echo "Created class-zoho-admin.php successfully.\n";
    } else {
        echo "Failed to create class-zoho-admin.php.\n";
    }
}
// Update class-zoho-crm-auth.php
$zoho_auth_file = $zoho_dir . '/class-zoho-crm-auth.php';
echo "\nChecking for class-zoho-crm-auth.php...\n";
if (file_exists($zoho_auth_file)) {
    echo "Found at $zoho_auth_file\n";
    
    // Backup the file
    $backup_file = $zoho_auth_file . '.bak.' . date('YmdHis');
    if (copy($zoho_auth_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of class-zoho-crm-auth.php\n";
    }
    
    // Read the file
    $auth_content = file_get_contents($zoho_auth_file);
    
    // Check if already patched
    if (strpos($auth_content, 'load_env_from_dotenv') === false) {
        echo "Patching class-zoho-crm-auth.php with environment loading...\n";
        
        // Find the beginning of the class definition
        $pattern = '/class HVAC_Zoho_CRM_Auth/';
        
        // Add environment loading function
        $replacement = "/**
 * Load environment variables from .env file
 */
function load_env_from_dotenv() {
    // Look for .env file in plugin directory and up to 3 levels up
    \$search_dirs = [
        dirname(dirname(dirname(__FILE__))), // Plugin directory
        dirname(dirname(dirname(dirname(__FILE__)))), // wp-content/plugins
        dirname(dirname(dirname(dirname(dirname(__FILE__))))), // wp-content
        dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))), // WordPress root
    ];
    
    foreach (\$search_dirs as \$dir) {
        \$env_file = \$dir . '/.env';
        if (file_exists(\$env_file)) {
            \$lines = file(\$env_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach (\$lines as \$line) {
                if (strpos(\$line, '=') \!== false && strpos(\$line, '#') \!== 0) {
                    list(\$name, \$value) = explode('=', \$line, 2);
                    \$name = trim(\$name);
                    \$value = trim(\$value);
                    
                    // Remove quotes if present
                    if (strpos(\$value, '\"') === 0 && strrpos(\$value, '\"') === strlen(\$value) - 1) {
                        \$value = substr(\$value, 1, -1);
                    } elseif (strpos(\$value, \"'\") === 0 && strrpos(\$value, \"'\") === strlen(\$value) - 1) {
                        \$value = substr(\$value, 1, -1);
                    }
                    
                    putenv(\"\$name=\$value\");
                    \$_ENV[\$name] = \$value;
                }
            }
            return true;
        }
    }
    return false;
}
class HVAC_Zoho_CRM_Auth";
        // Replace the class definition
        $auth_content = preg_replace($pattern, $replacement, $auth_content);
        
        // Find the constructor
        $constructor_pattern = '/public function __construct\(\) {/';
        $constructor_replacement = "public function __construct() {
        // Load environment variables from .env if available
        load_env_from_dotenv();";
        
        // Replace the constructor
        $auth_content = preg_replace($constructor_pattern, $constructor_replacement, $auth_content);
        
        // Add error logging to API requests
        $api_pattern = '/public function make_api_request\(\$endpoint, \$method = \'GET\', \$data = array\(\)\) {/';
        $api_replacement = "public function make_api_request(\$endpoint, \$method = 'GET', \$data = array()) {
        // Enhanced error logging
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] API Request: \$method \$endpoint\\n\";
            \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] Data: \" . json_encode(\$data) . \"\\n\";
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log(\$log_message, 3, ZOHO_LOG_FILE);
            }
        }";
        
        // Replace the API request method
        $auth_content = preg_replace($api_pattern, $api_replacement, $auth_content);
        
        // Add detailed logging to the API response
        $response_pattern = '/\$response = wp_remote_request\(\$url, \$args\);/';
        $response_replacement = "\$response = wp_remote_request(\$url, \$args);
        // Enhanced error logging
        if (defined('ZOHO_DEBUG_MODE') && ZOHO_DEBUG_MODE) {
            \$log_message = \"[\" . date('Y-m-d H:i:s') . \"] API Response Code: \" . wp_remote_retrieve_response_code(\$response) . \"\\n\";
            
            if (is_wp_error(\$response)) {
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] API Error: \" . \$response->get_error_message() . \"\\n\";
            } else {
                \$response_body = wp_remote_retrieve_body(\$response);
                \$log_message .= \"[\" . date('Y-m-d H:i:s') . \"] API Response Body: \" . substr(\$response_body, 0, 1000) . (strlen(\$response_body) > 1000 ? '...' : '') . \"\\n\";
            }
            
            if (defined('ZOHO_LOG_FILE')) {
                error_log(\$log_message, 3, ZOHO_LOG_FILE);
            }
        }";
        
        // Replace the response handling
        $auth_content = preg_replace($response_pattern, $response_replacement, $auth_content);
        
        // Add getter methods for credentials
        if (strpos($auth_content, 'get_client_id') === false) {
            $auth_content .= <<<'EOT'
    /**
     * Get client ID
     *
     * @return string
     */
    public function get_client_id() {
        return $this->client_id;
    }
    /**
     * Get client secret
     *
     * @return string
     */
    public function get_client_secret() {
        return $this->client_secret;
    }
    /**
     * Get refresh token
     *
     * @return string
     */
    public function get_refresh_token() {
        return $this->refresh_token;
    }
EOT;
        }
        
        // Save the updated file
        if (file_put_contents($zoho_auth_file, $auth_content)) {
            echo "Updated class-zoho-crm-auth.php successfully.\n";
        } else {
            echo "Failed to update class-zoho-crm-auth.php.\n";
        }
    } else {
        echo "class-zoho-crm-auth.php already patched.\n";
    }
} else {
    echo "Not found at $zoho_auth_file. Will not create a new file since it's too complex.\n";
}
// Create a diagnostic tool
$diagnostic_file = $zoho_dir . '/diagnostics.php';
echo "\nCreating Zoho diagnostics tool...\n";
$diagnostic_content = <<<'EOT'
get_access_token();
        echo "Token generation result: " . ($token && \!is_array($token) ? "Success (Token: " . substr($token, 0, 10) . "...)" : "Failed") . "\n";
        
        if (is_array($token) && isset($token['error'])) {
            echo "Error: " . $token['error'] . "\n";
            if (isset($token['details'])) {
                echo "Details: " . $token['details'] . "\n";
            }
        }
        
        // Test API connection
        echo "Testing API connection...\n";
        $modules = $zoho_auth->get_modules();
        if (is_array($modules) && \!isset($modules['error'])) {
            echo "API connection successful\!\n";
            echo "Available modules: " . (isset($modules['modules']) ? count($modules['modules']) : '0') . "\n";
            
            if (isset($modules['modules'])) {
                echo "Module names:\n";
                foreach ($modules['modules'] as $module) {
                    echo "  - " . $module['api_name'] . "\n";
                }
            }
        } else {
            echo "API connection failed\!\n";
            echo "Error details: " . print_r($modules, true) . "\n";
        }
    } catch (Exception $e) {
        echo "Exception: " . $e->getMessage() . "\n";
        echo "Stack trace: " . $e->getTraceAsString() . "\n";
    }
} else {
    echo "HVAC_Zoho_CRM_Auth class does not exist\!\n";
}
echo "\n";
echo "==========================================\n";
echo "Log File Contents (if available)\n";
echo "==========================================\n";
if (defined('ZOHO_LOG_FILE') && file_exists(ZOHO_LOG_FILE) && is_readable(ZOHO_LOG_FILE)) {
    echo "Log file found at: " . ZOHO_LOG_FILE . "\n";
    echo "Log file size: " . filesize(ZOHO_LOG_FILE) . " bytes\n";
    echo "Last 50 lines of log file:\n";
    
    $log_lines = file(ZOHO_LOG_FILE);
    $last_lines = array_slice($log_lines, -50);
    
    echo "-------------------------\n";
    foreach ($last_lines as $line) {
        echo $line;
    }
    echo "-------------------------\n";
} else {
    echo "Log file not found or not readable.\n";
}
echo "\n";
echo "==========================================\n";
echo "Diagnostics completed at " . date('Y-m-d H:i:s') . "\n";
echo "==========================================\n";
// Exit to prevent any further output
exit();
EOT;
if (file_put_contents($diagnostic_file, $diagnostic_content)) {
    echo "Created diagnostics.php successfully.\n";
} else {
    echo "Failed to create diagnostics.php.\n";
}
// Create CSS file for Zoho admin
$zoho_css_file = $css_dir . '/zoho-admin.css';
echo "\nChecking for zoho-admin.css...\n";
if (file_exists($zoho_css_file)) {
    echo "Found at $zoho_css_file\n";
    
    // Backup the file
    $backup_file = $zoho_css_file . '.bak.' . date('YmdHis');
    if (copy($zoho_css_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of zoho-admin.css\n";
    }
    
    // Read the file
    $css_content = file_get_contents($zoho_css_file);
    
    // Check if already patched
    if (strpos($css_content, 'hvac-zoho-debug-info') === false) {
        echo "Adding debug information styling to zoho-admin.css...\n";
        
        // Add debug information styling
        $css_content .= "\n\n/* Debug Information Styling */
.hvac-zoho-debug-info {
    margin-top: 15px;
    padding: 15px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-left: 4px solid #dc3232;
}
.hvac-zoho-debug-info details summary {
    cursor: pointer;
    font-weight: bold;
    color: #0073aa;
    padding: 5px;
    background: #f0f0f0;
}
.hvac-zoho-debug-info pre {
    margin: 10px 0;
    padding: 10px;
    background: #f0f0f0;
    border: 1px solid #ddd;
    overflow: auto;
    max-height: 300px;
}";
        
        // Save the updated file
        if (file_put_contents($zoho_css_file, $css_content)) {
            echo "Updated zoho-admin.css successfully.\n";
        } else {
            echo "Failed to update zoho-admin.css.\n";
        }
    } else {
        echo "zoho-admin.css already patched.\n";
    }
} else {
    echo "Not found at $zoho_css_file. Creating a new file...\n";
    
    // Create new zoho-admin.css
    $css_content = <<<'EOT'
/* Zoho Admin Styles */
.hvac-zoho-debug-info {
    margin-top: 15px;
    padding: 15px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-left: 4px solid #dc3232;
}
.hvac-zoho-debug-info details summary {
    cursor: pointer;
    font-weight: bold;
    color: #0073aa;
    padding: 5px;
    background: #f0f0f0;
}
.hvac-zoho-debug-info pre {
    margin: 10px 0;
    padding: 10px;
    background: #f0f0f0;
    border: 1px solid #ddd;
    overflow: auto;
    max-height: 300px;
}
EOT;
    if (file_put_contents($zoho_css_file, $css_content)) {
        echo "Created zoho-admin.css successfully.\n";
    } else {
        echo "Failed to create zoho-admin.css.\n";
    }
}
// Create JS file for Zoho admin
$zoho_js_file = $js_dir . '/zoho-admin.js';
echo "\nChecking for zoho-admin.js...\n";
if (file_exists($zoho_js_file)) {
    echo "Found at $zoho_js_file\n";
    
    // Backup the file
    $backup_file = $zoho_js_file . '.bak.' . date('YmdHis');
    if (copy($zoho_js_file, $backup_file)) {
        echo "Created backup at $backup_file\n";
    } else {
        echo "Failed to create backup of zoho-admin.js\n";
    }
    
    // Read the file
    $js_content = file_get_contents($zoho_js_file);
    
    // Check if already patched
    if (strpos($js_content, 'hvac-zoho-debug-info') === false) {
        echo "Patching zoho-admin.js with enhanced error display...\n";
        
        // Find the error handler
        $pattern = '/error: function\(response\) {([^}]+)}/s';
        
        // Add enhanced error display
        $replacement = "error: function(response) {
            $('#hvac-zoho-test-connection-result').empty();
            
            // Create detailed error display
            var errorHtml = '';
            errorHtml += '
' + response.data.message + ':  ' + response.data.error + '
';
            
            // Add error code if available
            if (response.data.code) {
                errorHtml += '
Error Code:  ' + response.data.code + '
';
            }
            
            // Add debugging info
            errorHtml += '
';
            // Add details if available
            if (response.data.details) {
                errorHtml += '
Details:  ' + response.data.details + '
';
            }
            
            // Add raw response data if available
            if (response.data.raw) {
                errorHtml += '
';
                errorHtml += 'Raw Response Data (click to expand) ';
                errorHtml += '' + JSON.stringify(JSON.parse(response.data.raw), null, 2) + ' ';
                errorHtml += ' ';
            }
            
            errorHtml += '
'; // Close debug info div
            errorHtml += '
' + hvac_zoho_admin.testing_connection + '
';
                    successHtml += '
' + response.data.message + ' 
';
                    
                    if (response.data.modules) {
                        successHtml += '
' + response.data.modules + '
';
                    }
                    
                    successHtml += '
Connection test failed. Please check the logs.
';
                errorHtml += '
' + response.data.message + ':  ' + response.data.error + '
';
                
                // Add error code if available
                if (response.data.code) {
                    errorHtml += '
Error Code:  ' + response.data.code + '
';
                }
                
                // Add debugging info
                errorHtml += '
';
                // Add details if available
                if (response.data.details) {
                    errorHtml += '
Details:  ' + response.data.details + '
';
                }
                
                // Add raw response data if available
                if (response.data.raw) {
                    errorHtml += '
';
                    errorHtml += 'Raw Response Data (click to expand) ';
                    errorHtml += '' + JSON.stringify(JSON.parse(response.data.raw), null, 2) + ' ';
                    errorHtml += ' ';
                }
                
                errorHtml += '
'; // Close debug info div
                errorHtml += '