<?php

namespace YOOtheme\Theme\Wordpress\Listener;

class LoadPostScript
{
    public static function handle($hook)
    {
        // is edit page, post?
        if (!in_array($hook, ['post.php', 'post-new.php'])) {
            return;
        }

        $url = get_template_directory_uri();
        $link = add_query_arg(
            ['url' => urlencode(get_permalink()), 'autofocus[section]' => 'builder'],
            wp_customize_url()
        );

        // redirect to customizer?
        if ($hook == 'post-new.php' && isset($_GET['yootheme-builder'])) {
            wp_redirect($link);
            exit();
        }

        add_action('edit_form_after_title', function ($post) use ($link) {
            printf(
                '<div class="tm-editor" hidden><a href="%s" class="tm-button">%s</a><a href class="tm-link">%s</a></div>',
                $link,
                __('YOOtheme Builder', 'yootheme'),
                __('&#8592; Back to Classic Editor', 'yootheme')
            );
        });

        add_action('media_buttons', function ($editor_id) use ($link) {
            if ($editor_id === 'content') {
                printf(
                    '<a href="%s" class="button button-primary">%s</a>',
                    $link,
                    __('YOOtheme Builder', 'yootheme')
                );
            }
        });

        add_filter('wp_editor_settings', function ($settings) {
            if (preg_match('/<!--\s?{/', get_post_field('post_content'))) {
                $settings['default_editor'] = 'html';
            }

            return $settings;
        });

        printf('<script>var $customizer = %s;</script>', json_encode(compact('link')));

        wp_enqueue_script(
            'posts-builder',
            "{$url}/vendor/yootheme/theme-wordpress-posts/app/posts.min.js",
            [],
            false,
            true
        );
    }
}
