<?php

function createblockfile_function()
{
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        return;
    }

    // Check if the user has submitted the settings
    if (isset($_GET['settings-updated'])) {
        add_settings_error('my_messages', 'my_message', __('Settings Saved', 'textdomain'), 'updated');
    }

    // Show error/update messages
    settings_errors('my_messages');
?>
    <style>
        .wrapCreateBLock {
            background-color: #FFF;
            padding: 20px;
            border-radius: 10px;
            width: 100%;
        }

        .avBlockOv {
            background-color: #FFF;
            padding: 20px;
            width: calc(100% - 120px);
            border-radius: 10px;
        }


        .wrapCreateBLock input {
            width: 100%;
            margin: 10px 0;
            height: 40px;
        }

        .wrapCreateBLock select {
            width: 100%;
            margin: 10px 0;
            height: 40px;
        }

        .wrapCreateBLock button {
            width: 100%;
            margin: 10px 0;
            height: 40px;
            background-color: #000;
            color: #FFF;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .container {
            max-width: 1200px !important;
            margin: 0;
            padding-inline: 15px;
        }

        .row {
            margin-top: 30px;
            margin-inline: -15px;
            display: flex;

        }

        .col-4 {
            flex: 0 0 auto;
            width: 29%;
            display: flex;
            padding-inline: 15px;
        }

        .col-8 {
            flex: 0 0 auto;
            width: 70%;
            display: flex;
            padding-inline: 15px;
        }

        .col-7 {
            flex: 0 0 auto;
            width: 60%;
            display: flex;
            padding-inline: 15px;
        }

        .col-5 {
            flex: 0 0 auto;
            width: 40%;
            display: flex;
            padding-inline: 15px;
        }

        .labelSm {
            font-size: 12px;
            color: #222;
        }

        .wrapCreatBlockOv h3,
        p {
            margin-block: 5px;
        }

        .blockSection {
            margin-top: 20px;
        }

        .epbWrapper {
            margin-top: 20px;
        }

        .editPossibleBlock {
            margin-top: 20px;
            background-color: #000;
            color: #FFF;
            padding: 10px 20px;
            border-radius: 5px;
            text-decoration: none;
        }

        .editPossibleBlock:hover {
            color: #FFF;
            background-color: #222;
        }

        .notice-warning-wrapper {
            background-color: rgb(239 68 68);
            color: #FFF;
            padding: 10px;

            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;

            margin-bottom: 20px;
        }

        .notice-warning-wrapper h1 {
            font-size: 20px;
            color: #FFF;
        }
    </style>

    <?php

    // if post blockname and filename is set
    if (isset($_POST['blockname']) && isset($_POST['filename'])) {
        $blockname = $_POST['blockname'];
        $filename = $_POST['filename'];

        $sanitized = sanitize_title($blockname);
        $functionName = str_replace('-', '_', strtolower($sanitized));

        $mode = $_POST['mode'];
        $pattern = $_POST['pattern'];
        $templateDirectory = get_template_directory() . '/blocks/templates/';
        $blockfile = $templateDirectory . $functionName . '.php';

        // Choose pattern
        if ($pattern === 'wp_query') {
            $blockcontent = file_get_contents($templateDirectory . 'patterns/' . 'pattern_wp_query.php');
        } else {
            $blockcontent = file_get_contents($templateDirectory . 'patterns/' . 'block.php');
        }

        // Check if the file already exists
        if (file_exists($blockfile)) {
            $count = 1;
            // Find an available file name by appending a counting number
            while (file_exists($templateDirectory . $functionName . '_' . $count . '.php')) {
                $count++;
            }
            // Update the blockfile path with the new available file name
            $blockfile = $templateDirectory . $functionName . '_' . $count . '.php';
            // Update the function name, block name, and filename to match the new file name
            $functionName = $functionName . '_' . $count;
            $blockname = $blockname . ' ' . $count;
            $filename = $filename . '_' . $count;
        }

        // Write the content to the file
        file_put_contents($blockfile, $blockcontent);

        $registerFilePath = get_template_directory() . '/blocks/register.php';

        // Check if the function is already registered
        $registerFileContent = file_get_contents($registerFilePath);
        if (strpos($registerFileContent, "function $functionName") === false) {
            $blockRegistrationCode = <<<PHP

    /**
     * Register function for: $blockname
     */
    add_action('acf/init', '$functionName');

    function $functionName()
    {
        // Register the $blockname ACF Block
        if (function_exists('acf_register_block')) {

            \$result = acf_register_block(array(
                'name'                => '$blockname',
                'title'                => __('$blockname'),
                'description'        => __('$blockname.'),
                'render_template'   => get_template_directory() . '/blocks/templates/$functionName.php',
                'category'            => 'theme_custom',
                'mode'                => '$mode',
            ));
        }
    };

    PHP;
            file_put_contents($registerFilePath, $blockRegistrationCode, FILE_APPEND);
        }

        // Prepare the URL with the updated blockname and filename
        $redirectUrl = "/wp-admin/post-new.php?post_type=acf-field-group&bsblockname=" . urlencode($blockname) . "&filename=" . urlencode($filename);
    ?>
        <script>
            window.location.href = "<?php echo $redirectUrl; ?>";
        </script>
    <?php
    }

    function parse_acf_register_blocks($fileContent)
    {
        // Regular expression to match the acf_register_block function call
        $pattern = '/acf_register_block\(\s*array\s*\((.*?)\)\s*\)\s*;/s';
        preg_match_all($pattern, $fileContent, $matches);

        $blocks = [];

        // Loop through each match
        foreach ($matches[1] as $block) {
            // Extract block details
            $namePattern = "/'name'\s*=>\s*'([^']+)'/";
            $templatePattern = "/'render_template'\s*=>\s*get_template_directory\(\)\s*\.\s*'([^']+)'/";

            preg_match($namePattern, $block, $nameMatch);
            preg_match($templatePattern, $block, $templateMatch);

            if (!empty($nameMatch) && !empty($templateMatch)) {
                $blocks[] = [
                    'name' => $nameMatch[1],
                    'template' => $templateMatch[1]
                ];
            }
        }

        return $blocks;
    }

    ?>

    <style>
        .blocknameInUse {
            color: red !important;
            border-color: red !important;
        }
    </style>

    <div class="wrapCreatBlockOv container">
        <!-- Write a warning that only developers should use this page -->
        <div class="notice-warning-wrapper">
            <h1><?php _e('This page is for developers only. Do not use this page if you are not a developer!', 'textdomain'); ?></h1>
        </div>
        <div class="row">
            <div class="col-4">
                <div class="wrapCreateBLock">
                    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
                    <div class="ajaxCreateBlockPHP">
                        <!-- form action this site -->
                        <form action="" method="post">
                            <div class="fyCenter">
                                <div>
                                    <input type="text" placeholder="Blockname" name="blockname" id="">
                                </div>
                                <div>
                                    <input type="text" placeholder="Filename" name="filename">
                                </div>
                                <div>
                                    <select name="mode" id="">
                                        <option value="auto">Auto</option>
                                        <option value="edit">Edit</option>
                                    </select>
                                </div>
                                <div>
                                    <select name="pattern" id="">
                                        <option value="block">Block</option>
                                        <option value="wp_query">WP Query</option>
                                    </select>
                                </div>
                                <div>
                                    <button id="createBlock" class="">Create Blockfiles</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-8">
                <div class="avBlockOv">
                    <h1 style="margin-bottom: 30px;">Avaiable Blocks</h1>
                    <div class="container">

                        <?php
                        // overciew (accordion) over all blocks from register php
                        $registerFilePath = get_template_directory() . '/blocks/register.php';
                        $registerFile = file_get_contents($registerFilePath);
                        $blocks = parse_acf_register_blocks($registerFile);
                        foreach ($blocks as $block) : ?>
                            <div class="row blockSection">
                                <div class="col-7">
                                    <div class="">
                                        <div class="labelSm">Name</div>
                                        <h3><?php echo htmlspecialchars($block['name']); ?></h3>
                                        <div class="labelSm">File</div>
                                        <p><?php echo htmlspecialchars($block['template']); ?></p>
                                    </div>
                                </div>

                                <div class="col-5">
                                    <div>
                                        <div class="labelSm">Possible Block</div>

                                        <div class="epbWrapper">
                                            <?php $hasBlock = get_acf_field_group_id($block['name']);
                                            if ($hasBlock) {
                                                echo '<a class="editPossibleBlock" href="' . admin_url('post.php?post=' . $hasBlock . '&action=edit') . '">Edit Block</a>';
                                            } else {
                                                echo 'No Block';
                                            }
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>

                    </div>

                </div>
            </div>
        </div>
    </div>

    <script>
        jQuery(function($) {
            $(document).ready(function() {
                function sanitizeTitle(title) {
                    // Convert specific German umlauts to their equivalents
                    title = title.replace(/ä/g, 'ae')
                        .replace(/ö/g, 'oe')
                        .replace(/ü/g, 'ue')
                        .replace(/ß/g, 'ss')
                        .replace(/Ä/g, 'Ae')
                        .replace(/Ö/g, 'Oe')
                        .replace(/Ü/g, 'Ue');

                    // Convert to lowercase
                    title = title.toLowerCase();

                    // Replace accented characters with their basic counterparts
                    title = title.normalize('NFD').replace(/[\u0300-\u036f]/g, '');

                    // Replace spaces and other non-alphanumeric characters with underscores
                    title = title.replace(/[^a-z0-9]+/g, '-');

                    // Remove leading and trailing underscores
                    title = title.replace(/^_+|_+$/g, '');

                    return title;
                }


                // when block name looes focus, convert to slug and fill filename
                $('input[name="blockname"]').on('blur', function() {
                    var blockname = $(this).val();
                    var filename = sanitizeTitle(blockname);
                    $('input[name="filename"]').val(filename);
                });

                // On leave of input[name="blockname"], check every $('.blockSection h3'). If blockname is already in use, add class .blocknameInUse to input[name="blockname"]. If not, remove class .blocknameInUse.
                $('input[name="blockname"]').on('blur', function() {
                    var blockname = $(this).val();
                    var blocknameInUse = false;
                    $('.blockSection h3').each(function() {
                        if ($(this).text() === blockname) {
                            blocknameInUse = true;
                        }
                    });

                    if (blocknameInUse) {
                        $(this).addClass('blocknameInUse');
                        alert('Blockname already in use. You can create it but the system will append a number to the blockname and file upon creation.');
                    } else {
                        $(this).removeClass('blocknameInUse');
                    }
                });


            });
        });
    </script>
    <?php
}


function blockCreateInsertValues()
{
    if (isset($_POST['bsaction']) && $_POST['bsaction'] === 'mirrorvalues') {
        $post_id = $_POST['mvalid'];
        check_acf_field_group_creation($post_id, false);
    }
    // if current single post type is acf-field-group
    if (get_post_type() === 'acf-field-group') {
        // check if post id is set
        if (isset($_GET['post']) && !empty($_GET['post'])) {
            $post_id = $_GET['post'];
            $notin = check_acf_field_group_creation($post_id);

            if ($notin) {
    ?>
                <style>
                    .transferValues {
                        text-decoration: none;
                        position: fixed;
                        bottom: 20px;
                        right: 20px;
                        cursor: pointer;
                        z-index: 9999;
                    }

                    .transferValues button {
                        background-color: #000;
                        color: #FFF;
                        border: none;
                        border-radius: 5px;
                        cursor: pointer;
                        padding: 20px 25px;
                    }

                    .transferValues button:hover {
                        background-color: #222;
                        border-radius: 5px;
                    }

                    .transferValues.inactive {
                        display: none;
                    }
                </style>

                <div class="transferValues">
                    <form action="" method="post">
                        <input type="hidden" name="mvalid" value="<?php echo $post_id; ?>">
                        <input type="hidden" name="bsaction" value="mirrorvalues">
                        <button>
                            Mirror Values to PHP
                        </button>
                    </form>
                </div>
                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        const mirrorButton = document.getElementById('mirrorButton');
                        const transferValues = document.querySelector('.transferValues');

                        function invalidateMirrorButton() {
                            transferValues.classList.add('inactive');
                        }

                        // Observe changes in ACF fields
                        const observer = new MutationObserver(invalidateMirrorButton);
                        const config = {
                            attributes: true,
                            childList: true,
                            subtree: true
                        };

                        function observeFields() {
                            document.querySelectorAll('.acf-field').forEach(field => {
                                observer.observe(field, config);
                            });
                        }

                        // Initially observe existing fields
                        observeFields();

                        // Listen to input events
                        document.querySelectorAll('.acf-field input, .acf-field textarea, .acf-field select').forEach(input => {
                            input.addEventListener('input', invalidateMirrorButton);
                        });

                        // Handle adding new ACF fields dynamically
                        jQuery(document).on('acf/field_group/add_field', function() {
                            observeFields();
                        });

                        // Listen to changes in the field group for added fields
                        jQuery('.acf-field-list').on('DOMNodeInserted', function() {
                            observeFields();
                        });
                    });
                </script>
            <?php } ?>
        <?php
        }
    }

    // if get param bsblockname is set and not empty and param filname is set and not empty, set title val and select option from select class refresh-location-rule to option value block and acf/filename to select with location-rule-value option value block
    if (isset($_GET['bsblockname']) && !empty($_GET['bsblockname']) && isset($_GET['filename']) && !empty($_GET['filename'])) {
        $blockname = esc_html($_GET['bsblockname']);
        $filename = esc_html($_GET['filename']);
        $filename = str_replace('_', '-', $filename);

        ?>
        <style>
            .lds-dual-ring,
            .lds-dual-ring:after {
                box-sizing: border-box;
            }

            .lds-dual-ring {
                display: inline-block;
                width: 80px;
                height: 80px;
            }

            .lds-dual-ring:after {
                content: " ";
                display: block;
                width: 64px;
                height: 64px;
                margin: 8px;
                border-radius: 50%;
                border: 6.4px solid currentColor;
                border-color: currentColor transparent currentColor transparent;
                animation: lds-dual-ring 1.2s linear infinite;
            }

            @keyframes lds-dual-ring {
                0% {
                    transform: rotate(0deg);
                }

                100% {
                    transform: rotate(360deg);
                }
            }

            .preloader {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(255, 255, 255, 0.8);
                z-index: 9999;
                display: none;
                justify-content: center;
                align-items: center;
            }

            .preloader.active {
                display: flex;
            }
        </style>
        <!-- fixed Preloader over the page with class active -->
        <div class="preloader active">
            <div class="lds-dual-ring">

            </div>
        </div>

        <script type="text/javascript">
            (function($) {
                $(document).ready(function() {
                    // Set title value
                    $('#title').val('<?php echo $blockname; ?>');

                    // Select option with value 'block' in select class 'refresh-location-rule'
                    $('.refresh-location-rule option[value="block"]').prop('selected', true).trigger('change');

                    // Function to set the desired option after changes
                    function setDesiredOption() {
                        $('select.location-rule-value option[value="acf/<?php echo $filename; ?>"]').prop('selected', true);
                    }

                    // Create a MutationObserver to watch for changes in the tbody element
                    var observer = new MutationObserver(function(mutations) {
                        mutations.forEach(function(mutation) {
                            if (mutation.type === 'childList') {
                                setDesiredOption();
                            }
                        });
                    });

                    // Observe changes in the tbody element
                    var target = document.querySelector('.acf-field-settings tbody');
                    if (target) {
                        observer.observe(target, {
                            childList: true,
                            subtree: true
                        });
                    }

                    // Initially set the desired option in case the elements are already loaded
                    setDesiredOption();

                    setTimeout(function() {
                        console.log('Timeout setDesiredOption');
                        $('.preloader').removeClass('active');
                        setDesiredOption();
                    }, 2000);
                });
            })(jQuery);
        </script>
<?php
    }
}

add_action('admin_notices', 'blockCreateInsertValues');


// function to check if $block['name'] from foreach loop matches with a title from cpt acf-field-group and if so, return id of cpt
function get_acf_field_group_id($blockname)
{
    $args = array(
        'post_type' => 'acf-field-group',
        'posts_per_page' => -1,
    );

    $field_groups = get_posts($args);

    foreach ($field_groups as $field_group) {
        $title = get_the_title($field_group->ID);
        if ($title === $blockname) {
            return $field_group->ID;
        }
    }

    return false;
}




function check_acf_field_group_creation($post_id, $check = true)
{

    $post = get_post($post_id);

    // Check if it's an ACF field group post type and if it's newly created
    if ($post->post_type == 'acf-field-group') {
        // Get the location rule value
        $pc = $post->post_content;

        $decoded_array = unserialize($pc);


        $location_rules = $decoded_array['location'] ?? null;


        if (!empty($location_rules) && is_array($location_rules)) {
            foreach ($location_rules as $location_rule_group) {
                foreach ($location_rule_group as $location_rule) {
                    if (isset($location_rule['param']) && $location_rule['param'] == 'block') {
                        $block_name = str_replace('acf/', '', $location_rule['value']);
                        $block_name = str_replace('-', '_', $block_name);
                        $template_file_path = get_template_directory() . "/blocks/templates/{$block_name}.php";
                        if (file_exists($template_file_path)) {
                            if ($check) {
                                $template_content = file_get_contents($template_file_path);
                                if (strpos($template_content, "/**createdwithblockautomation*/") !== false) {
                                    return true;
                                }
                                return false;
                            } else {
                                replace_placeholder_with_field_values($template_file_path, $post_id);
                            }
                        }
                    }
                }
            }
        }
    }
}



function replace_placeholder_with_field_values($template_file_path, $field_group_id)
{
    $fields = acf_get_fields($field_group_id);
    if (!$fields) return;

    $field_assignments = "";

    foreach ($fields as $field) {
        $field_name = $field['name'];
        $field_assignments .= "\${$field_name} = get_field('{$field_name}');\n";
    }

    $template_content = file_get_contents($template_file_path);
    $updated_content = str_replace("/**createdwithblockautomation*/", $field_assignments, $template_content);

    file_put_contents($template_file_path, $updated_content);
}
