<?php

/**
 * Register Meta Box for the plugin
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    Movies
 * @subpackage Movies/includes
 */

/**
 * Register Meta Box for the plugin.
 *
 * Meta box shown in custom post type Movies
 *
 * @package    Movies
 * @subpackage Movies/includes
 * @author     Your Name <email@example.com>
 */
class Movies_Meta_Box {

    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
        add_action( 'save_post', array( $this, 'save_meta_box' ) );
    }

    public function add_meta_box() {
        add_meta_box(
            'movie_title',
            __('Enter Movie Title', 'movies' ),
            array( $this, 'render_meta_box' ),
            'movies',
            'side',
            'default',
	        array(
		        'default_hidden' => false,
	        )
        );
    }

    public function render_meta_box( $post ) {
        wp_nonce_field( 'movie_title_nonce', 'movie_title_nonce' );

        $movie_title = get_post_meta( $post->ID, 'movie_title', true );
        ?>
        <label for="movie_title"><?php _e( 'Movie Title', 'movies' ); ?></label>
        <input type="text" id="movie_title" name="movie_title" value="<?php echo esc_attr( $movie_title ); ?>" />
        <?php
    }

    public function save_meta_box( $post_id ) {
        if ( !isset( $_POST['movie_title_nonce'] ) ) {
            return;
        }

        if ( !wp_verify_nonce( $_POST['movie_title_nonce'], 'movie_title_nonce' ) ) {
            return;
        }

        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        if ( isset( $_POST['post_type'] ) && 'movies' === $_POST['post_type'] ) {
            if ( !current_user_can( 'edit_post', $post_id ) ) {
                return;
            }

            if ( !isset( $_POST['movie_title'] ) ) {
                return;
            }

            $movie_title = sanitize_text_field( $_POST['movie_title'] );
            update_post_meta( $post_id, 'movie_title', $movie_title );
        }
    }
}
new Movies_Meta_Box();
?>

