<?php

namespace auctionforge\inc\controllers;

use auctionforge\inc\abs\Model;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\model\Lot;
use auctionforge\inc\model\LotMetaData;
use WP_Post;

class MetaBoxViewHomepage
{
    const SEO_METABOX_NONCE = 'seo_metabox_view_homepage_nonce';

    public function init()
    {
        add_action('admin_menu', array($this, 'lotview_homepage_meta_boxes'));
        add_action('save_post', array($this, 'lotview_homepage_meta_boxes_save'));
    }

    public function lotview_homepage_meta_boxes() {
        add_meta_box('lotview_homepageboxdiv', __('Display lot on the main page', 'auctionforge'), array($this, 'lot_view_homepage_print_box'), 'lot', 'side', 'default');
    }

    /**
     * @param $post WP_Post
     */
    public function lot_view_homepage_print_box($post) {
        wp_nonce_field(basename( __FILE__ ), self::SEO_METABOX_NONCE);

        $saved = LotMetaData::getMetaField(Lot::VIEW_HOMEPAGE_BS, $post->ID);
        $id = Lot::VIEW_HOMEPAGE_BS;

        if(Model::toBoolean($saved)) {
            $saved = true;
        } else {
            $saved = false;
        }

        echo View::render('admin.view.meta_box_view_homepage', array(
            'saved' => $saved,
            'id' => $id,
            'label' => __('Lot will be displayed on the main page', 'auctionforge') . "."
        ));
    }

    public function lotview_homepage_meta_boxes_save( $post_id )
    {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }

        if (empty($_POST[self::SEO_METABOX_NONCE]) || !wp_verify_nonce( $_POST[self::SEO_METABOX_NONCE], basename( __FILE__ ))) {
            return;
        }

        if ( isset($_POST[Lot::VIEW_HOMEPAGE]) || is_null($_POST[Lot::VIEW_HOMEPAGE]) ) {
            $this->meta_boxes_save_BS($post_id);
        }
    }

    private function meta_boxes_save_BS($post_id)
    {
        $data = array(
            "featured" => !is_null($_POST[Lot::VIEW_HOMEPAGE_BS])
        );
        LotMetaData::updateField($data, $post_id, "%d");

        if ((PolylangSupport::isPolylangActive() && PolylangSupport::isFullSupport())) {
            $secondPosts = pll_get_post_translations($post_id);
            if (!empty($secondPosts)) {
                foreach ($secondPosts as $secondPost) {
                    LotMetaData::updateField($data, $secondPost, "%d");
                }
            }
        }
    }
}
$metaBox = new MetaBoxViewHomepage();
$metaBox->init();
