<?php

function createentity_function()
{
?>
    <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;
        }

        .fyCenter {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 54px;
            height: 28px;
            margin-right: 10px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
        }

        input:checked+.slider {
            background-color: #000;
        }

        input:checked+.slider:before {
            transform: translateX(26px);
        }

        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }

        .switchWrap {
            margin: 10px 0;
            transition: .2s ease-in;
        }

        .switchWrap.inactive {
            opacity: .7;
            pointer-events: none;
            cursor: not-allowed;
        }

        .naTypes {
            color: #666;
            font-size: 20px;
            width: 100%;
            aspect-ratio: 4/3;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .naTypes div {
            display: block;
        }

        .naTypes>div div {
            display: flex;
            justify-content: center;
        }
    </style>
    <?php
    if (isset($_POST['cptname'])) {
        $cpt = $_POST['cptname'];
        // check for needsAjax, separate_js and separate_func
        $needsAjax = isset($_POST['needsAjax']) ? true : false;
        $separate_js = isset($_POST['separate_js']) ? true : false;
        $separate_func = isset($_POST['separate_func']) ? true : false;
        create_cpt_files($cpt, $needsAjax, $separate_js, $separate_func);
    ?>
        <script>
            // window.location.href = "/wp-admin/post-new.php?post_type=acf-field-group&bsblockname=<?php echo $blockname; ?>&filename=<?php echo $filename; ?>";
        </script>
    <?php
    }
    ?>
    <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">
                <?php $avTypes = checkAvTypes(false);

                ?>
                <div class="wrapCreateBLock">
                    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
                    <?php
                    if (empty($avTypes)) {
                        echo '<p class="naTypes">No custom types available</p>';
                    } else {
                    ?>
                        <div class="ajaxCreateBlockPHP">
                            <!-- form action this site -->
                            <form action="" method="post">
                                <div class="">
                                    <div>
                                        <select name="cptname" id="">
                                            <?php

                                            foreach ($avTypes as $avType) {
                                                echo '<option value="' . $avType['cptname'] . '">' . $avType['cpttitle'] . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="switchWrap">
                                        <label class="switch">
                                            <input type="checkbox" name="separate_js">
                                            <span class="slider round"></span>
                                        </label>
                                        <label for="separate_js">Separate JS file?</label>
                                    </div>
                                    <div class="switchWrap">
                                        <label class="switch">
                                            <input type="checkbox" name="separate_func">
                                            <span class="slider round"></span>
                                        </label>
                                        <label for="separate_func">Separate Function file?</label>
                                    </div>
                                    <div class="switchWrap inactive">
                                        <label class="switch">
                                            <input type="checkbox" name="needsAjax">
                                            <span class="slider round"></span>
                                        </label>
                                        <label for="needsAjax">Func/JS Ajax?</label>
                                    </div>
                                    <div>
                                        <button id="createBlock">Create Blockfiles</button>
                                    </div>
                                </div>
                            </form>

                        </div>
                    <?php
                    }
                    ?>
                </div>
            </div>
            <div class="col-8">
                <div class="avBlockOv">
                    <h1 style="margin-bottom: 30px;">Custom Type Files</h1>
                    <div class="container">

                        <?php
                        // overciew (accordion) over all blocks from register php
                        $blocks = checkAvTypes();
                        if (empty($blocks)) {
                            echo '<div class="naTypes"><div><div>No custom type files available</div>';
                            // insert wrapped button to crate new cpt: /wp-admin/post-new.php?post_type=acf-post-type
                            echo  '<div><a href="/wp-admin/post-new.php?post_type=acf-post-type" class="editPossibleBlock">Create New CPT</a></div></div></div>';
                        } else {
                            foreach ($blocks as $block) : ?>
                                <div class="row blockSection">
                                    <div class="">
                                        <div class="">
                                            <div class="labelSm">Name</div>
                                            <h3><?php echo htmlspecialchars($block['cpttitle']); ?></h3>
                                            <div class="labelSm">Folder</div>
                                            <p>/entities/<?php echo htmlspecialchars($block['cptname']); ?></p>
                                        </div>
                                    </div>
                                </div>
                        <?php endforeach;
                        }
                        ?>

                    </div>

                </div>
            </div>
        </div>
    </div>
    <script>
        jQuery(function($) {
            $(document).ready(function() {
                // on change of checkboxes: if js and func is checked, remove needsAjax switchwrap class "inactive", else add
                $('input[name="separate_js"], input[name="separate_func"]').change(function() {
                    if ($('input[name="separate_js"]').is(':checked') && $('input[name="separate_func"]').is(':checked')) {
                        $('input[name="needsAjax"]').closest('.switchWrap').removeClass('inactive');
                    } else {
                        $('input[name="needsAjax"]').closest('.switchWrap').addClass('inactive');
                        // also uncheck needsAjax
                        $('input[name="needsAjax"]').prop('checked', false);
                    }
                });

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

function checkAvTypes($isAv = true)
{
    $avTypes = array();
    $btypes = array();
    // get all from cpt acf-post-type
    $args = array(
        'post_type' => 'acf-post-type',
        'posts_per_page' => -1,
    );
    $posts = get_posts($args);
    // for each posts add to btypes array if  post_excerpt doesnt match with a folder in /entities/ 
    foreach ($posts as $post) {
        $post_excerpt = $post->post_excerpt;
        $folder_path = get_template_directory() . '/entities/' . $post_excerpt;
        if (!is_dir($folder_path)) {
            $btypes[] = array(
                'cptname' => $post_excerpt,
                'cpttitle' => $post->post_title,
            );
        } else {
            $avTypes[] = array(
                'cptname' => $post_excerpt,
                'cpttitle' => $post->post_title,
            );
        }
    }
    if ($isAv) {
        return $avTypes;
    } else {
        return $btypes;
    }
}


function create_cpt_files($cpt_name, $needsAjax, $separate_js, $separate_func)
{
    $theme_dir = get_template_directory();
    $entities_dir = $theme_dir . '/entities/' . $cpt_name;

    if (file_exists($entities_dir)) {
        wp_die('Directory already exists, check manually!', 'Directory Exists', array('back_link' => true));
    }

    if (!mkdir($entities_dir, 0755, true)) {
        wp_die('Failed to create directory, check permissions!', 'Directory Creation Failed', array('back_link' => true));
    }

    // Content of single-myCPT.php - get it from the single.php file
    $single_template = file_get_contents(get_template_directory() . '/single.php');

    // Write single-myCPT.php
    file_put_contents($entities_dir . '/single-' . $cpt_name . '.php', $single_template);

    // Content of myCPT.js
    if ($separate_js) {
        if ($needsAjax) {
            $js_content = <<<JS
jQuery(function($) {
    $(document).ready(function () {
        // Your JavaScript code for {$cpt_name}

        // Example AJAX call
        /*
        $.ajax({
            url: ajaxurl, // or your custom URL
            method: 'POST',
            data: {
                action: 'handle_{$cpt_name}_ajax',
                // additional data
            },
            success: function(response) {
                console.log(response);
            }
        });
        */
    });
});
JS;
        } else {
            $js_content = <<<JS
jQuery(function($) {
    $(document).ready(function () {
        // Your JavaScript code for {$cpt_name}
    });
});
JS;
        }
        file_put_contents($entities_dir . '/' . $cpt_name . '.js', $js_content);
    }

    if ($separate_func) {
        $func_content = "<?php // Your PHP function code for " . $cpt_name . "\n";
        if ($needsAjax) {
            $ajax_function_name = 'handle_' . str_replace('-', '_', sanitize_title($cpt_name)) . '_ajax';
            $func_content .= <<<PHP

// Register AJAX handlers for the {$cpt_name} CPT
add_action('wp_ajax_{$ajax_function_name}', '{$ajax_function_name}');
add_action('wp_ajax_nopriv_{$ajax_function_name}', '{$ajax_function_name}');

function {$ajax_function_name}() {
    // Your AJAX handling code here
    wp_send_json_success('AJAX request handled successfully.');
}
PHP;
        }
        file_put_contents($entities_dir . '/' . $cpt_name . '-functions.php', $func_content);
    }

    // Append the function to register.php
    append_register_function($cpt_name, $needsAjax, $separate_js, $separate_func);

    wp_die('Files created successfully!', 'Success', array('back_link' => true));
}
function append_register_function($cpt_name, $needsAjax, $separate_js, $separate_func)
{
    $register_file_path = get_template_directory() . '/entities/register.php';
    $function_name = 'use_custom_single_' . str_replace('-', '_', sanitize_title($cpt_name)) . '_template';

    $register_code = <<<PHP

// Register the custom template for the {$cpt_name} CPT
function {$function_name}(\$template) {
    if (is_singular('{$cpt_name}')) { // Check if the current post type is '{$cpt_name}'
        \$custom_template = get_template_directory() . '/entities/{$cpt_name}/single-{$cpt_name}.php';
        if (file_exists(\$custom_template)) {
            return \$custom_template; // Use the custom template if it exists
        }
    }
    return \$template; // Fallback to the default template if the custom template does not exist
}
add_filter('template_include', '{$function_name}');
PHP;

    if ($separate_js) {
        $register_code .= <<<PHP

// Enqueue script for the {$cpt_name} CPT
function enqueue_{$cpt_name}_scripts() {
    wp_enqueue_script('{$cpt_name}-script', get_template_directory_uri() . '/entities/{$cpt_name}/{$cpt_name}.js', array('jquery'), null, true);
PHP;

        if ($needsAjax) {
            $register_code .= <<<PHP
    wp_localize_script('{$cpt_name}-script', 'ajax_object', array(
        'ajaxurl' => admin_url('admin-ajax.php')
    ));
PHP;
        }

        $register_code .= <<<PHP
}
add_action('wp_enqueue_scripts', 'enqueue_{$cpt_name}_scripts');
PHP;
    }

    if ($separate_func) {
        $register_code .= <<<PHP

// Include custom functions for the {$cpt_name} CPT
require get_template_directory() . '/entities/{$cpt_name}/{$cpt_name}-functions.php';
PHP;
    }

    // Append the register code to the register.php file
    file_put_contents($register_file_path, $register_code, FILE_APPEND);
}


?>