<?php
/**
 * Attachments helper functions.
 *
 * @package Nisje
 */

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

/**
 * Get Post Attachments
 *
 * @param WP_Post $post The object from the response.
 * @return mixed
 */
function nisje_get_post_attachments( $post ) {
	$post_id = false;

	$retval = [
		'attachments' => [],
		'total'       => 0,
	];

	if ( is_object( $post ) ) {
		$post_id = $post->ID;
	}

	if ( is_array( $post ) ) {
		$post_id = $post['id'];
	}

	if ( ! $post_id ) {
		return $retval;
	}

	$attachment_ids = maybe_unserialize( get_post_meta( $post_id, 'attachments', true ) );
	$attachments    = [];

	if ( ! $attachment_ids ) {
		return $retval;
	}

	foreach ( $attachment_ids as $id ) {
		$attachment = get_post( $id );

		if ( $attachment instanceof \WP_Post && 'attachment' === $attachment->post_type ) {
			$attached_file = get_attached_file( $attachment->ID );

			$attachments[] = [
				'id'      => $id,
				'url'     => wp_get_attachment_url( $id ),
				'title'   => $attachment->post_title,
				'type'    => $attachment->post_mime_type,
				'size'    => file_exists( $attached_file ) ? size_format( filesize( $attached_file ) ) : 0,
				'preview' => wp_get_attachment_image_url( $id ),
			];
		}
	}

	$retval = [
		'attachments' => $attachments,
		'total'       => count( $attachments ),
	];

	return $retval;
}

/**
 * Update Attachments
 *
 * @param mixed   $field The object from the response.
 * @param WP_Post $post  The object from the response.
 *
 * @return mixed
 */
function nisje_update_post_attachments( $field, $post ) {
	$post_id = false;

	$retval = [
		'attachments' => [],
		'total'       => 0,
	];

	if ( is_object( $post ) ) {
		$post_id = $post->ID;
	}

	if ( is_array( $post ) ) {
		$post_id = $post['id'];
	}

	if ( ! $post_id ) {
		return $retval;
	}

	if ( empty( $field ) ) {
		delete_post_meta( $post_id, 'attachments' );
		return $retval;
	}

	update_post_meta( $post_id, 'attachments', maybe_serialize( $field ) );

	$retval = [
		'attachments' => $field,
		'total'       => count( $field ),
	];

	/**
	 * Fires after attachments are connected to a post.
	 *
	 * @param mixed   $field The object from the response.
	 * @param WP_Post $post  The object from the response.
	 */
	do_action( 'nisje_update_post_attachments', $field, $post );

	return $retval;
}
