<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Vserpb_AssociatedMediaObject {

	private $media_url;
	private $media_name;
	private $media_description;
	private $media_mime;
	private $media_width;
	private $media_height;

	/**
	 * @param int $attachment_id WordPress attachment ID
	 */
	public function __construct( $attachment_id ) {

		$attachment_id = absint( $attachment_id );

		if ( ! $attachment_id ) {
			return;
		}

		$this->media_url  = wp_get_attachment_url( $attachment_id );
		$this->media_name = get_the_title( $attachment_id );

		$post = get_post( $attachment_id );
		if ( $post ) {
			$this->media_description = $post->post_excerpt ?: $post->post_content;
		}

		$this->media_mime = get_post_mime_type( $attachment_id );

		$meta = wp_get_attachment_metadata( $attachment_id );

		// Only for visual media (image / video)
		if ( ! empty( $meta['width'] ) ) {
			$this->media_width = (int) $meta['width'];
		}

		if ( ! empty( $meta['height'] ) ) {
			$this->media_height = (int) $meta['height'];
		}
	}

	/**
	 * @return array
	 */
	public function vserpb_getSchema() {

		if ( empty( $this->media_url ) ) {
			return array();
		}

		$schema = array(
			'@type'      => 'MediaObject',
			'contentUrl' => esc_url( $this->media_url ),
			'name'       => sanitize_text_field( $this->media_name ),
		);

		if ( ! empty( $this->media_description ) ) {
			$schema['description'] = sanitize_textarea_field( wp_strip_all_tags( $this->media_description ) );
		}

		if ( ! empty( $this->media_mime ) ) {
			$schema['encodingFormat'] = $this->media_mime;
		}

		// Width / Height only when available (images / video)
		if ( ! empty( $this->media_width ) ) {
			$schema['width'] = $this->media_width;
		}

		if ( ! empty( $this->media_height ) ) {
			$schema['height'] = $this->media_height;
		}

		return $schema;
	}
}
