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

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

if ( class_exists( 'Dekode_BP_Attachment' ) ) :
	/**
	 * Attachment Expire Class
	 */
	class Dekode_Expire_BP_Attachment extends Dekode_BP_Attachment {
		/**
		 * Expire time
		 *
		 * @var int
		 */
		public $expire_time;

		/**
		 * Dekode_Expire_BP_Attachment Constructor.
		 * Construct and set default expire time of attachment
		 *
		 * @param array $args        Constructor arguments.
		 * @param int   $expire_time Expire time.
		 */
		public function __construct( $args = [], $expire_time = 120 ) {
			parent::__construct( $args );
			$this->expire_time = $expire_time;
		}

		/**
		 * 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 ) {
			$result = parent::upload( $file, $upload_dir_filter, $time );

			add_post_meta( $this->attachment_id, 'Dekode_Expire_BP_Attachment', $this->expire_time, true );

			$result['url'] = wp_get_attachment_url( $this->attachment_id );

			return $result;
		}

		/**
		 * Set what folder to upload to based on id of current user. Also put it in folder with secure link enabled.
		 *
		 * @param array $upload_dir Upload Dir.
		 *
		 * @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 . '/ex/' . bp_loggedin_user_id(),
				'url'     => $this->url . '/ex/' . bp_loggedin_user_id(),
				'subdir'  => '/ex/' . bp_loggedin_user_id(),
				'basedir' => $this->upload_path . '/ex/' . bp_loggedin_user_id(),
				'baseurl' => $this->url . '/ex/' . bp_loggedin_user_id(),
				'error'   => false,
			];
		}
	}

endif;
