<?php

defined('ABSPATH') or die('No script kiddies please!!');
if (!class_exists('STD_Metabox')) {

    class STD_Metabox extends STD_Library {

        function __construct() {
            add_action('add_meta_boxes', array($this, 'add_std_metabox'));
            add_action('save_post', array($this, 'save_std_metabox'), 10, 2);
        }

        function add_std_metabox() {
            add_meta_box('std-metabox', esc_html__('Subscribe to Download', 'subscribe-to-download'), array($this, 'render_std_metabox'), array(), 'side', 'default');
        }

        function render_std_metabox($post) {
            include(STD_PATH . 'inc/views/backend/std-metabox.php');
        }

        /**
         * Handles saving the meta box.
         *
         * @param int     $post_id Post ID.
         * @param WP_Post $post    Post object.
         * @return null
         *
         * @since 1.0.0
         */
        public function save_std_metabox($post_id, $post) {

            // Check if nonce is valid.
            if (empty($_POST['std_metabox_nonce_field'])) {
                return;
            }
            if (!wp_verify_nonce($_POST['std_metabox_nonce_field'], 'std_metabox_nonce')) {
                return;
            }

            // Check if user has permissions to save data.
            if (!current_user_can('edit_post', $post_id)) {
                return;
            }

            // Check if not an autosave.
            if (wp_is_post_autosave($post_id)) {
                return;
            }

            // Check if not a revision.
            if (wp_is_post_revision($post_id)) {
                return;
            }

            if (empty($_POST['std_metabox_details'])) {
                return;
            }

            $std_metabox_details = $this->sanitize_array($_POST['std_metabox_details']);
            update_post_meta($post_id, '_std_metabox_details', $std_metabox_details);
        }

    }

    new STD_Metabox();
}
