<?php

add_action( 'wp_ajax_wiaas_upload_file', 'wiaas_ajax_upload_document_version' );
add_action( 'wp_ajax_wiaas_quick_add_document', 'wiaas_ajax_quick_add_document' );
add_action( 'wp_ajax_wiaas_link_document', 'wiaas_ajax_link_document' );

add_action( 'wp_ajax_wiaas_json_search_documents','wiaas_ajax_json_search_documents' );


/**
 * Upload document version file with ajax
 */
function wiaas_ajax_upload_document_version() {
	check_ajax_referer('wiaas_upload_file');

	if (!isset($_FILES['wiaas_file']) || empty($_FILES['wiaas_file'])) {
		echo "ERROR: No file present!";
		die();
	}

	$version = Wiaas_Document_Upload::upload_document_version('wiaas_file');

	if (is_wp_error($version)) {
		echo 'ERROR:' . $version->get_error_message();
		die();
	}

	echo $version;
	die();
}

/**
 * Quick add new document and return attachment view for it
 */
function wiaas_ajax_quick_add_document() {
	check_ajax_referer('wiaas_quick_add_document');

	//validate file
	if (!isset($_FILES['wiaas_file']) || empty($_FILES['wiaas_file'])) {
		echo "ERROR: No file present!";
		die();
	}

	// Upload document version file
	$version = Wiaas_Document_Upload::upload_document_version('wiaas_file');

	// Upload failed so return the error
	if (is_wp_error($version)) {
		echo 'ERROR:' . $version->get_error_message();
		die();
	}

	// Get document title
	$title = isset($_POST['doc_title']) && $_POST['doc_title'] !== '' ?
		sanitize_text_field($_POST['doc_title']) :
		pathinfo( $version, PATHINFO_FILENAME );

	// Try to create new document
	$id = Wiaas_Document::add_document(
		$title,
		$version,
		$_POST['doc_visible'] === 'true');

	// Document creation failed so return the error
	if (!$id) {
		echo "ERROR: Document could not be created!";
		die();
	}

	// If document type is sent then assign new document to it
	if (isset($_POST['doc_type'])) {
		Wiaas_Document::set_doc_type( $id, sanitize_key($_POST['doc_type']) );
	}

	require 'views/html-attached-document.php';

	die();
}

/**
 * Render attacment view for linked document
 */
function wiaas_ajax_link_document() {
	check_ajax_referer('wiaas_link_document');

	$id = absint($_GET['id']);

	require 'views/html-attached-document.php';

	die();
}

/**
 *
 *Search wiaas documents by name
 */
function wiaas_ajax_json_search_documents() {
	check_ajax_referer('wiaas_json_search_documents');

	$q = ( ! empty( $_GET['query'] ) ? sanitize_text_field($_GET['query']) : '' );

	$result = Wiaas_Document::search($q);

	wp_send_json( $result );
}