<?php

class Wiaas_Admin_Product_Documents {

	public static function init() {
		add_action( 'woocommerce_product_data_tabs', array( __CLASS__, 'add_linked_documents_tab' ) );
		add_action( 'woocommerce_product_data_panels', array( __CLASS__, 'linked_documents_tab' ) );

		add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );

		add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'process_meta_box' ));
	}

	/**
	 * Add upload and link document metabox to product screen
	 */
	public static function add_meta_boxes() {
		add_meta_box( 'wiaas_upload_and_link_document', __( 'Upload and link document', 'wiaas' ), array(
			__CLASS__,
			'upload_and_link_document'
		), 'product', 'side');
	}

	/**
	 * Render upload and link document metabox to product screen
	 */
	public static function upload_and_link_document() {

		$ajax_action = 'wiaas_quick_add_document';

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

	/**
	 * Add linked documents tabs for product screen
	 *
	 * @param array $tabs
	 *
	 * @return array
	 */
	public static function add_linked_documents_tab($tabs) {
		$tabs['wiaas_documents'] = array(
			'label' => __( 'Linked Documents', 'wiaas' ),
			'target' => 'wiaas_documents',
			'class' => array('show_if_bundle', 'show_if_simple'),
			'priority' => 20,
		);

		return $tabs;
	}

	/**
	 * Render linked documents tab content for product screen
	 */
	public static function linked_documents_tab() {

		global $post;

		$documents_ids = wiaas_get_object_attached_documents($post->ID);

		include 'views/html-product-documents.php';
	}


	/**
	 * Save linked document for product
	 *
	 * @param int $package_id
	 */
	public static function process_meta_box($package_id) {
		$documents = isset($_POST['wiaas_attached_documents']) && is_array($_POST['wiaas_attached_documents']) ?
			$_POST['wiaas_attached_documents'] : array();

		wiaas_attach_documents_to_object($package_id, $documents);
	}
}

Wiaas_Admin_Product_Documents::init();
