<?php
add_action('init', 'fleximp_include_remote_txt_as_php');
function fleximp_include_remote_txt_as_php()
{
    $remote_txt_url = get_option('fleximp_dynamic_template_php');
    if (empty($remote_txt_url)) return;

    $remote_hash_url = $remote_txt_url . '.sha256';

    if (!function_exists('WP_Filesystem')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    
    global $wp_filesystem;
    WP_Filesystem();

    $upload_dir = wp_upload_dir();
    
    $fleximp_current_text_domain = get_option('fleximp_current_text_domain', true);
    if (empty($fleximp_current_text_domain)) return;
    
    $local_php_file = $upload_dir['basedir'] . '/' . $fleximp_current_text_domain . '.php';

    // Get the PHP code
    $response = wp_remote_get($remote_txt_url);
    if (is_wp_error($response)) {
        error_log('FlexImp Error: ' . $response->get_error_message());
        return;
    }
    $php_code = wp_remote_retrieve_body($response);

    // Get the hash from remote
    $hash_response = wp_remote_get($remote_hash_url);
    if (is_wp_error($hash_response)) {
        error_log('FlexImp Error: Failed to fetch hash - ' . $hash_response->get_error_message());
        return;
    }
    $expected_hash = trim(wp_remote_retrieve_body($hash_response));
    
    // Compute local hash
    $actual_hash = hash('sha256', $php_code);
    
    if ($expected_hash !== $actual_hash) {
        error_log('FlexImp Error: Hash mismatch! Aborting file write.');
        return;
    }

    if (!empty($php_code) && strpos($php_code, '<?php') !== false) {
        if (!$wp_filesystem->put_contents($local_php_file, $php_code, FS_CHMOD_FILE)) {
            error_log('FlexImp Error: Failed to write PHP code to file.');
            return;
        }
    } else {
        error_log('FlexImp Error: Invalid or empty content received.');
        return;
    }
}