<?php
// if GET cptname not empty, trigger the functions and redirect to /wp-admin/edit.php?post_type=cptname
if (isset($_GET['cptname']) && !empty($_GET['cptname'])) {
    create_cpt_files($_GET['cptname']);
    register_new_cpt($_GET['cptname']);
    wp_redirect(admin_url('edit.php?post_type=' . $_GET['cptname']));
    exit;
}




function register_new_cpt($cpt_name)
{
    $register_path = get_template_directory() . '/entities/register.php';
    $function_name = 'register_' . str_replace('-', '_', sanitize_title($cpt_name));
    $block_registration_code = <<<PHP

/**
 * Register function for: $cpt_name
 */
add_action('acf/init', '$function_name');

function $function_name()
{
    // Register the $cpt_name ACF Block
    if (function_exists('acf_register_block')) {
        \$result = acf_register_block(array(
            'name'                => '$cpt_name',
            'title'                => __('$cpt_name'),
            'description'        => __('$cpt_name.'),
            'render_template'   => get_template_directory() . '/blocks/templates/$cpt_name.php',
            'category'            => 'theme_custom',
            'mode'                => 'auto',
        ));
    }
};

PHP;

    // Append the new block registration code to register.php
    file_put_contents($register_path, $block_registration_code, FILE_APPEND);

    // echo "Block registered successfully.";
}
