<?php
/**
 * Avatars Base class
 *
 * @package Nisje
 */

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

/**
 * Avatar
 */
final class Nisje_Avatar {
	/**
	 * ID
	 *
	 * @var int
	 */
	public $id = '';

	/**
	 * Type
	 *
	 * @var string
	 */
	public $type = '';

	/**
	 * Src
	 *
	 * @var array
	 */
	public $src = [];

	/**
	 * Default Src
	 *
	 * @var string
	 */
	public $default_src = [];

	/**
	 * Constructor
	 *
	 * @param int    $id    ID.
	 * @param string $type  Type.
	 * @param bool   $fetch Fetch.
	 */
	public function __construct( $id, $type, $fetch = true ) {
		$this->id   = absint( $id );
		$this->type = sanitize_key( $type );

		$this->set_path();
		$this->set_url();

		if ( $fetch ) {
			$this->fetch_avatar();
			if ( ! $this->fetch_default_avatar() ) {
				$default_type = 'png';
				if ( 'group' === $type ) {
					$default_type = 'text';
				}

				$this->add_default_avatar( $default_type );
			}
		}
	}

	/**
	 * Set Paths
	 */
	private function set_path() {
		$path = trailingslashit( bp_core_avatar_upload_path() );

		if ( 'user' === $this->type ) {
			$dir = 'avatars';
		} else {
			$dir = 'group-avatars';
		}

		$this->path = $path . $dir . '/' . $this->id;

		$this->default_path = $path . $dir . '/' . $this->id . '/default';
	}

	/**
	 * Set URLs
	 */
	private function set_url() {
		$url = trailingslashit( bp_core_avatar_url() );

		if ( 'user' === $this->type ) {
			$dir = 'avatars';
		} else {
			$dir = 'group-avatars';
		}

		$this->url = esc_url( $url . $dir . '/' . $this->id );

		$this->default_url = esc_url( $url . $dir . '/' . $this->id . '/default' );
	}

	/**
	 * Fetch Avatar
	 */
	private function fetch_avatar() {
		if ( file_exists( $this->path ) ) {
			$av_dir = opendir( $this->path );
			if ( $av_dir ) {
				$avatar_files = [];

				while ( false !== ( $avatar_file = readdir( $av_dir ) ) ) { // phpcs:ignore
					if ( 2 < strlen( $avatar_file ) ) {
						$avatar_files[] = $avatar_file;
					}
				}

				$this->src = $this->parse_avatar_files( $avatar_files, $this->url );
			}

			closedir( $av_dir );
		}

		if ( empty( $this->src ) ) {
			$this->src = [];
		}
	}

	/**
	 * Fetch Default Avatar
	 */
	public function fetch_default_avatar() {
		if ( file_exists( $this->default_path ) ) {
			$av_dir = opendir( $this->default_path );
			if ( $av_dir ) {
				$avatar_files = [];

				while ( false !== ( $avatar_file = readdir( $av_dir ) ) ) { // phpcs:ignore
					if ( 2 < strlen( $avatar_file ) && 'default' !== $avatar_file ) {
						$avatar_files[] = $avatar_file;
					}
				}

				$this->default_src = $this->parse_avatar_files( $avatar_files, $this->default_url );
			}

			// Close the avatar directory.
			closedir( $av_dir );
		}

		if ( empty( $this->default_src ) ) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Parse Avatar files.
	 *
	 * @param array  $avatar_files Avatars.
	 * @param string $url          URL.
	 *
	 * @return array Avatars
	 */
	private function parse_avatar_files( $avatar_files, $url ) {
		if ( is_array( $avatar_files ) && 0 < count( $avatar_files ) ) {
			$sizes   = nisje_get_avatar_sizes();
			$avatars = [];

			foreach ( $avatar_files as $key => $value ) {
				foreach ( $sizes as $size_key => $size ) {
					if ( strpos( $value, $size_key ) !== false ) {
						$avatars[ $size_key ] = esc_url( $url . '/' . $avatar_files[ $key ] );
					} elseif ( strpos( $value, 'bporg' ) !== false ) {
						$avatars['org'] = esc_url( $url . '/' . $avatar_files[ $key ] );
					}
				}
			}

			return $avatars;
		}

		return [];
	}

	/**
	 * Add Default Avatars
	 *
	 * @param string $default_type Text/Image.
	 */
	private function add_default_avatar( $default_type ) {
		if ( ! file_exists( $this->default_path ) ) {
			if ( ! wp_mkdir_p( $this->default_path ) ) {
				return;
			}
		}

		if ( 'png' === $default_type ) {
			$this->add_default_png_avatar();
		}
	}

	/**
	 * Add Default PNG Avatar
	 */
	private function add_default_png_avatar() {
		$colors = nisje_get_setting( 'default_avatar_colors', 'general' );
		if ( $colors && 'grey' === $colors ) {
			$png_path = 'png-user-avatars-grey';
		} else {
			$png_path = 'png-user-avatars-color';
		}

		$rand          = wp_rand( 0, 49 );
		$random_avatar = nisje_get_path( 'assets/default-avatars/' . $png_path . '/av' . $rand . '.png' );

		if ( file_exists( $random_avatar ) ) {
			// Get the file extension.
			$data     = getimagesize( $random_avatar );
			$ext      = 'image/png' === $data['mime'] ? 'png' : 'jpg';
			$filename = wp_unique_filename( $this->default_path, uniqid() . "-bporg.{$ext}" );
			$dest     = $this->default_path . '/' . $filename;

			copy( $random_avatar, $dest );

			$this->default_src['org'] = esc_url( $this->default_url . '/' . basename( $dest ) );

			foreach ( nisje_get_avatar_sizes() as $key => $size ) {
				$image = wp_get_image_editor( $dest );
				if ( ! is_wp_error( $image ) ) {
					$image->resize( $size['width'], $size['height'], true );
					$filename = wp_unique_filename( $this->default_path, uniqid() . "-bp{$key}.{$ext}" );
					$new_dest = $this->default_path . '/' . $filename;
					$image->save( $new_dest );
					$this->default_src[ $key ] = esc_url( $this->default_url . '/' . basename( $new_dest ) );
				}
			}
		}
	}
}
