<?php
function irpp_ui_metabox($post) {
    global $irpp;

    wp_nonce_field('irpp_meta_box', 'irpp_meta_box_nonce');
    $array=$irpp->Options->getExcludedPostsIds();
    $exclude=FALSE;
    if(in_array($post->ID, $array)) {
        $exclude=TRUE;
    }
    ?>
    <input type="hidden" name="irpp_previous" value="<?php echo ($exclude ? 1 : 0)?>" />
    <input type="checkbox" class="irpp-checkbox" name="irpp_exclude" value="1" <?php echo ($exclude ? ' CHECKED' : '')?> />
    <?php $irpp->Lang->P('نوشته بدون درج نوشته مرتبط')?>
    <?php
}

add_action('add_meta_boxes', 'irpp_add_meta_box');
function irpp_add_meta_box() {
    global $irpp;

    $options=$irpp->Options->getMetaboxPostTypes();
    $screens=array();
    foreach($options as $k=>$v) {
        if(intval($v)>0) {
            $screens[]=$k;
        }
    }
    if(count($screens)>0) {
        foreach ($screens as $screen) {
            add_meta_box(
                'irpp_sectionid'
                , $irpp->Lang->L('Related Posts by IntellyWP')
                , 'irpp_ui_metabox'
                , $screen
                , 'side'
            );
        }
    }
}
//si aggancia a quando un post viene salvato per salvare anche gli altri dati del metabox
add_action('save_post', 'irpp_save_meta_box_data');
function irpp_save_meta_box_data($postId) {
    global $irpp;

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!isset($_POST['irpp_meta_box_nonce']) || !isset($_POST['post_type'])) {
        return;
    }
    if (!wp_verify_nonce( $_POST['irpp_meta_box_nonce'], 'irpp_meta_box')) {
        return;
    }

    $exclude=$irpp->Utils->qs('irpp_exclude', 0);
    $previous=$irpp->Utils->qs('irpp_previous', 0);
    if($exclude!=$previous) {
        $array=$irpp->Options->getExcludedPostsIds();
        $array=array_diff($array, array($postId));
        if($exclude) {
            array_push($array, $postId);
        }
        $irpp->Options->setExcludedPostsIds($array);
    }
}
