<?php

/**
 * Editor for wiaas document post screen
 *
 * Class Wiaas_Admin_Document_Editor
 */
class Wiaas_Admin_Document_Editor {

	public static function init() {
		add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );

		add_action( 'save_post', array( __CLASS__, 'save' ), 1, 2 );
	}


	/**
	 * Add wiaas document editor metaboxes
	 */
	public static function add_meta_boxes() {

		add_meta_box( 'wiaas_document_details', __( 'Details', 'wiaas' ), array(
			__CLASS__,
			'document_info'
		), 'wiaas_doc', 'normal', 'low');
	}

	/**
	 * Save wiaas document informations
	 * @param $post_id
	 * @param $post
	 */
	public static function save ($post_id, $post) {
		if ( empty( $post_id ) || empty( $post ) || empty( $_POST ) ) {
			return;
		}
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( is_int( wp_is_post_revision( $post ) ) ) {
			return;
		}
		if ( is_int( wp_is_post_autosave( $post ) ) ) {
			return;
		}
		if ( empty( $_POST['wiaas_doc_nonce'] ) || ! wp_verify_nonce( $_POST['wiaas_doc_nonce'], 'save_wiaas_doc' ) ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( $post->post_type != 'wiaas_doc' ) {
			return;
		}

		// unset nonce because it's only valid of 1 post
		unset( $_POST['wiaas_doc_nonce'] );

		if (isset($_POST['wiaas_doc_version']) && $_POST['wiaas_doc_version'] !== '') {
			$version = sanitize_text_field($_POST['wiaas_doc_version']);

			if(wiaas_document_version_exists($version)) {
				Wiaas_Document::add_document_version($post_id, $version);
			}
		}

		if (isset($_POST['wiaas_doc_type'])) {
			Wiaas_Document::set_doc_type($post_id, sanitize_key($_POST['wiaas_doc_type']));
		}

		Wiaas_Document::set_is_doc_visible($post_id, $_POST['wiaas_doc_visible'] === 'on');
	}

	/**
	 * Render wiaas document info metabox
	 */
	public static function document_info() {
		global $post;

		$parent_post_type = $post->post_type;
		$document_id = $post->ID;

		$ajax_action = 'wiaas_upload_file';

		require 'views/html-document-info.php';
	}

}

Wiaas_Admin_Document_Editor::init();
