<?php

namespace RtmBusiness\PostSync;

use WordpressModels\Assets;
use WordpressModels\PostMetaBox;
use WP_Post;
use WP_Screen;

class MetaBoxHandler extends PostMetaBox
{

    /**
     * @param Assets $assets The assets instance to use for enquing the scripts
     * @param string $postType The post type for which to enable the metabox
     */
    public function __construct(Assets $assets, string $postType)
    {
        parent::__construct('rtm-sync-metabox', 'RTM PostSync', $postType, 'side', 'default', ['postsync'], $assets);

        add_action('admin_enqueue_scripts', [$this, 'enqueue_meta_box_scripts']);
    }

    /**
     * Enqueues the JavaScript for a custom meta box in the post editing screens.
     * @param string $hook_suffix The current admin page, passed from admin_enqueue_scripts hook.
     * @return void
     */
    public function enqueue_meta_box_scripts(string $hook_suffix)
    {
        if ('post.php' == $hook_suffix || 'post-new.php' == $hook_suffix) {
            $this->enqueueScripts();

            //Only enqueue WP-Components styles if gutenburg block editor is disabled for current page
            if (WP_Screen::get($hook_suffix)->is_block_editor === false) {
                wp_enqueue_style(
                    'wp-components',
                    get_site_url() . '/wp-includes/css/dist/components/style.min.css',
                    array(),
                    wp_get_theme()->get('Version')
                );
            }

            wp_localize_script('postsync', 'WP_REST', [
                'url' => get_rest_url(),
                'nonce' => wp_create_nonce('wp_rest'),
                'debug' => wp_get_environment_type() === 'development'
            ]);


        }
    }


    /**
     * Renders the placeholder element for the metabox which is then replace in postsync.js
     * @param WP_Post $post The post currently being editted
     * @return void
     */
    public function renderMetaBox(WP_Post $post): void
    {
        echo '<div id="postsync-metabox-content"></div>';
    }
}
