<?php

namespace RtmBusiness\PostSync;

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

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();

            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>';
    }
}
