<?php
/**
 * Dekode BP Attachment Class
 *
 * @package Nisje
 */

defined( 'ABSPATH' ) || die( 'Shame on you' );

if ( class_exists( 'BP_Attachment' ) ) :
	/**
	 * Attachment Base Class
	 */
	class Dekode_BP_Attachment extends BP_Attachment {
		/**
		 * Filename
		 *
		 * @var string
		 */
		protected $filename;

		/**
		 * Attachment ID
		 *
		 * @var int
		 */
		public $attachment_id;

		/**
		 * Dekode_BP_Attachment Constructor
		 *
		 * @param array $args Constructor arguments.
		 */
		public function __construct( $args = [] ) {
			$standard_args = [
				'action'     => 'dk_attachments_upload',
				'file_input' => 'dk_attachment_file',
				'base_dir'   => 'attachments',
			];

			parent::__construct( array_merge( $standard_args, $args ) );

			// Override upload array to be able to change filename.
			add_filter( 'dekode_attachment_upload_overrides', [ $this, 'upload_overrides' ] );
		}

		/**
		 * Upload image and return result
		 *
		 * @param array  $file              File.
		 * @param string $upload_dir_filter Upload dir filter.
		 * @param null   $time              Time.
		 *
		 * @return array
		 */
		public function upload( $file, $upload_dir_filter = '', $time = null ) {
			// Store original filename.
			$this->filename = $file[ $this->file_input ]['name'];

			$result = parent::upload( $file, $upload_dir_filter, $time );

			$this->attachment_id = $this->create_attachment();

			unset( $result['file'] );

			$result['id']    = $this->attachment_id;
			$result['title'] = $this->filename;

			return $result;
		}

		/**
		 * Further sanitize
		 *
		 * @param  string $retval Filename.
		 *
		 * @return string
		 */
		public function sanitize_utf8_filename( $retval ) {
			$retval = parent::sanitize_utf8_filename( $retval );
			return str_replace( '?', '', $retval );
		}

		/**
		 * Function to change $override variable
		 *
		 * @param array $overrides Upload overrides.
		 *
		 * @return array
		 */
		public function upload_overrides( $overrides ) {
			return $overrides;
		}

		/**
		 * Create attachment based on file uploaded
		 *
		 * @return int ID of attachment
		 */
		private function create_attachment() {
			$name = $this->filename;
			$ext  = pathinfo( $name, PATHINFO_EXTENSION );
			$name = wp_basename( $name, ".$ext" );

			$post_data = [];

			if ( isset( $this->document_id ) ) {
				// Override guid fo attachment created.
				$post_data = [
					'guid'        => get_permalink( $this->document_id ),
					'post_parent' => $this->document_id,
				];
			}

			if ( ! isset( $this->attachment['url'] ) ) {
				return;
			}

			$url     = $this->attachment['url'];
			$type    = $this->attachment['type'];
			$file    = $this->attachment['file'];
			$title   = sanitize_text_field( $name );
			$content = '';
			$excerpt = '';

			$post_id = 0;

			// Construct the attachment array.
			$attachment = array_merge( [
				'post_mime_type' => $type,
				'guid'           => $url,
				'post_parent'    => $post_id,
				'post_title'     => $title,
				'post_content'   => $content,
				'post_excerpt'   => $excerpt,
			], $post_data );

			// This should never be set as it would then overwrite an existing attachment.
			unset( $attachment['ID'] );

			if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
				include ABSPATH . 'wp-admin/includes/image.php';
			}

			// Save the data.
			$id = wp_insert_attachment( $attachment, $file, $attachment['post_parent'] );
			if ( ! is_wp_error( $id ) ) {
				$metadata = wp_generate_attachment_metadata( $id, $file );

				$metadata = $this->add_metadata( $metadata );

				wp_update_attachment_metadata( $id, $metadata );
			}

			return $id;
		}

		/**
		 * Handle metadata of attachment
		 *
		 * @param array $metadata Attachment data.
		 *
		 * @return array
		 */
		private function add_metadata( $metadata ) {
			return $metadata;
		}

		/**
		 * Set what folder to upload to based on id of current user.
		 *
		 * @param array $upload_dir Upload directory.
		 *
		 * @return array
		 */
		public function upload_dir_filter( $upload_dir = [] ) {

			$upload_dir_data = parent::upload_dir_filter();

			if ( ! is_user_logged_in() ) {
				return $upload_dir_data;
			}

			// Set upload dir with filter.
			return [
				'path'    => $this->upload_path . '/no/' . bp_loggedin_user_id(),
				'url'     => $this->url . '/no/' . bp_loggedin_user_id(),
				'subdir'  => '/no/' . bp_loggedin_user_id(),
				'basedir' => $this->upload_path . '/no/' . bp_loggedin_user_id(),
				'baseurl' => $this->url . '/no/' . bp_loggedin_user_id(),
				'error'   => false,
			];

		}
	}

endif;
