<?php
// Prevent loading this file directly
defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'THE7_RWMB_File_Field' ) )
{
	class THE7_RWMB_File_Field
	{
		/**
		 * Enqueue scripts and styles
		 *
		 * @return void
		 */
		static function admin_enqueue_scripts()
		{
			static $vars_localized;

			wp_enqueue_style( 'the7-mb-file', THE7_RWMB_CSS_URL . 'file.css', array(), THE7_RWMB_VER );
			wp_enqueue_script( 'the7-mb-file', THE7_RWMB_JS_URL . 'file.js', array( 'jquery', 'wp-ajax-response' ), THE7_RWMB_VER, true );
			if ( ! $vars_localized ) {
				wp_localize_script( 'the7-mb-file', 'the7mbFile', array(
					'maxFileUploadsSingle' => __( 'You may only upload maximum %d file', 'the7mk2' ),
					'maxFileUploadsPlural' => __( 'You may only upload maximum %d files', 'the7mk2' ),
				) );
				$vars_localized = true;
			}
		}

		/**
		 * Add actions
		 *
		 * @return void
		 */
		static function add_actions()
		{
			// Add data encoding type for file uploading
			add_action( 'post_edit_form_tag', array( __CLASS__, 'post_edit_form_tag' ) );

			// Delete file via Ajax
			add_action( 'wp_ajax_the7_mb_delete_file', array( __CLASS__, 'wp_ajax_delete_file' ) );
		}

		/**
		 * Add data encoding type for file uploading
		 *
		 * @return void
		 */
		static function post_edit_form_tag()
		{
			echo ' enctype="multipart/form-data"';
		}

		/**
		 * Ajax callback for deleting files.
		 * Modified from a function used by "Verve Meta Boxes" plugin
		 *
		 * @link https://goo.gl/LzYSq
		 * @return void
		 */
		static function wp_ajax_delete_file()
		{
			$post_id       = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0;
			$field_id      = isset( $_POST['field_id'] ) ? The7_RW_Meta_Box::sanitize_ajax_field_id( $_POST['field_id'] ) : '';
			$attachment_id = isset( $_POST['attachment_id'] ) ? absint( wp_unslash( $_POST['attachment_id'] ) ) : 0;

			check_ajax_referer( "the7-mb-delete-file_{$field_id}" );

			$field = The7_RW_Meta_Box::get_authorized_ajax_field(
				$post_id,
				$field_id,
				array( 'file', 'file_advanced', 'image', 'image_advanced', 'plupload_image', 'thickbox_image' )
			);
			if ( ! $field || ! $attachment_id || ! The7_RW_Meta_Box::field_contains_attachment_ids( $post_id, $field, array( $attachment_id ) ) ) {
				The7_RW_Meta_Box::ajax_response( __( 'Error: Cannot delete file', 'the7mk2' ), 'error' );
			}

			$force_delete = ! empty( $field['force_delete'] );
			if ( $force_delete && ! current_user_can( 'delete_post', $attachment_id ) ) {
				The7_RW_Meta_Box::ajax_response( __( 'Error: Cannot delete file', 'the7mk2' ), 'error' );
			}

			$ok = $force_delete ? wp_delete_attachment( $attachment_id ) : true;
			if ( $ok ) {
				The7_RW_Meta_Box::remove_attachment_from_field( $post_id, $field, $attachment_id );
			}

			if ( $ok )
				The7_RW_Meta_Box::ajax_response( '', 'success' );
			else
				The7_RW_Meta_Box::ajax_response( __( 'Error: Cannot delete file', 'the7mk2' ), 'error' );
		}

		/**
		 * Get field HTML
		 *
		 * @param string $html
		 * @param mixed  $meta
		 * @param array  $field
		 *
		 * @return string
		 */
		static function html( $html, $meta, $field )
		{
			$i18n_title = apply_filters( 'the7_mb_file_upload_string', _x( 'Upload Files', 'file upload', 'the7mk2' ), $field );
			$i18n_more  = apply_filters( 'the7_mb_file_add_string', _x( '+ Add new file', 'file upload', 'the7mk2' ), $field );

			// Uploaded files
			$html = self::get_uploaded_files( $meta, $field );
			$new_file_classes = array( 'new-files' );
			if ( !empty( $field['max_file_uploads'] ) && count( $meta ) >= (int) $field['max_file_uploads'] )
				$new_file_classes[] = 'hidden';

			// Show form upload
			$html .= sprintf(
				'<div class="%s">
					<h4>%s</h4>
					<div class="file-input"><input type="file" name="%s[]" /></div>
					<a class="the7-mb-add-file" href="#"><strong>%s</strong></a>
				</div>',
				implode( ' ', $new_file_classes ),
				$i18n_title,
				$field['id'],
				$i18n_more
			);

			return $html;
		}

		static function get_uploaded_files( $files, $field )
		{
			$delete_nonce = wp_create_nonce( "the7-mb-delete-file_{$field['id']}" );
			$classes = array('the7-mb-file', 'the7-mb-uploaded');
			if ( count( $files ) <= 0  )
				$classes[] = 'hidden';
			$ol = '<ul class="%s" data-field_id="%s" data-delete_nonce="%s" data-force_delete="%s" data-max_file_uploads="%s" data-mime_type="%s">';
			$html = sprintf(
				$ol,
				implode( ' ', $classes ),
				$field['id'],
				$delete_nonce,
				$field['force_delete'] ? 1 : 0,
				$field['max_file_uploads'],
				$field['mime_type']
			);

			foreach ( $files as $attachment_id )
			{
				$html .= self::file_html( $attachment_id );
			}

			$html .= '</ul>';

			return $html;
		}

		static function file_html( $attachment_id )
		{
			$i18n_delete = apply_filters( 'the7_mb_file_delete_string', _x( 'Delete', 'file upload', 'the7mk2' ) );
			$i18n_edit   = apply_filters( 'the7_mb_file_edit_string', _x( 'Edit', 'file upload', 'the7mk2' ) );
			$li = '
			<li>
				<div class="the7-mb-icon">%s</div>
				<div class="the7-mb-info">
					<a href="%s" target="_blank">%s</a>
					<p>%s</p>
					<a title="%s" href="%s" target="_blank">%s</a> |
					<a title="%s" class="the7-mb-delete-file" href="#" data-attachment_id="%s">%s</a>
				</div>
			</li>';

			$mime_type = get_post_mime_type( $attachment_id );
			return sprintf(
				$li,
				wp_get_attachment_image( $attachment_id, array(60,60), true ),
				wp_get_attachment_url($attachment_id),
				get_the_title( $attachment_id ),
				$mime_type,
				$i18n_edit,
				get_edit_post_link( $attachment_id ),
				$i18n_edit,
				$i18n_delete,
				$attachment_id,
				$i18n_delete
			);
		}

		/**
		 * Get meta values to save
		 *
		 * @param mixed $new
		 * @param mixed $old
		 * @param int   $post_id
		 * @param array $field
		 *
		 * @return array|mixed
		 */
		static function value( $new, $old, $post_id, $field )
		{
			$name = $field['id'];
			if ( empty( $_FILES[ $name ] ) )
				return $new;

			$new = array();
			$files	= self::fix_file_array( $_FILES[ $name ] );

			foreach ( $files as $file_item )
			{
				$file = wp_handle_upload( $file_item, array( 'test_form' => false ) );

				if ( ! isset( $file['file'] ) )
					continue;

				$file_name = $file['file'];

				$attachment = array(
					'post_mime_type' => $file['type'],
					'guid'           => $file['url'],
					'post_parent'    => $post_id,
					'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
					'post_content'   => '',
				);
				$id = wp_insert_attachment( $attachment, $file_name, $post_id );

				if ( ! is_wp_error( $id ) )
				{
					wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file_name ) );

					// Save file ID in meta field
					$new[] = $id;
				}
			}

			return array_unique( array_merge( $old, $new ) );
		}

		/**
		 * Fixes the odd indexing of multiple file uploads from the format:
		 *	 $_FILES['field']['key']['index']
		 * To the more standard and appropriate:
		 *	 $_FILES['field']['index']['key']
		 *
		 * @param array $files
		 *
		 * @return array
		 */
		static function fix_file_array( $files )
		{
			$output = array();
			foreach ( $files as $key => $list )
			{
				foreach ( $list as $index => $value )
				{
					$output[$index][$key] = $value;
				}
			}
			return $output;
		}

		/**
		 * Normalize parameters for field
		 *
		 * @param array $field
		 *
		 * @return array
		 */
		static function normalize_field( $field )
		{
			$field = wp_parse_args( $field, array(
				'std'              => array(),
				'force_delete'     => false,
				'max_file_uploads' => 0,
				'mime_type'        => '',
			) );
			$field['multiple'] = false;
			return $field;
		}

		/**
		 * Standard meta retrieval
		 *
		 * @param mixed $meta
		 * @param int   $post_id
		 * @param array $field
		 * @param bool  $saved
		 *
		 * @return mixed
		 */
		static function meta( $meta, $post_id, $saved, $field )
		{
//			$meta = The7_RW_Meta_Box::meta( $meta, $post_id, $saved, $field );
			$meta = get_post_meta( $post_id, $field['id'], true );

			if ( empty( $meta ) )
				return array();

			return (array) $meta;
		}
	}
}
