<?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 ) {
			$attachments[] = [
				'id'    => $id,
				'url'   => wp_get_attachment_url( $id ),
				'title' => $attachment->post_title,
				'type'  => $attachment->post_mime_type,
			];
		}
	}

	$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;
}
