<?php
/**
 * Resource handler for COupons data.
 *
 * @since 2.8.3
 */

namespace Masteriyo\Addons\Coupons\Resources;

use Masteriyo\Helper\Utils;
use Masteriyo\Resources\UserResource;

defined( 'ABSPATH' ) || exit;

/**
 * Resource handler for Coupons data.
 *
 * @since 2.8.3
 */
class CouponsResource {

	/**
	 * Transform the resource into an array.
	 *
	 * @since 2.8.3
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupons object.
	 *
	 * @return array
	 */
	public static function to_array( $coupon, $context = 'view' ) {

		$user = masteriyo_get_user( $coupon->get_author_id( $context ) );

		if ( ! is_wp_error( $user ) ) {
			$author = array(
				'id'           => $user->get_id(),
				'display_name' => $user->get_display_name(),
				'avatar_url'   => $user->profile_image_url(),
			);
		}

		$data = array(
			'code'                   => $coupon->get_code(),
			'description'            => $coupon->get_description(),
			'author_id'              => $coupon->get_author_id(),
			'created_at'             => masteriyo_rest_prepare_date_response( $coupon->get_created_at() ),
			'modified_at'            => masteriyo_rest_prepare_date_response( $coupon->get_modified_at() ),
			'status'                 => $coupon->get_status(),
			'discount_type'          => $coupon->get_discount_type(),
			'discount_amount'        => $coupon->get_discount_amount(),
			'usage_limit_per_user'   => $coupon->get_usage_limit_per_user(),
			'usage_limit_per_coupon' => $coupon->get_usage_limit_per_coupon(),
			'usage_count'            => $coupon->get_usage_count(),
			'start_at'               => masteriyo_rest_prepare_date_response( $coupon->get_start_at() ),
			'expire_at'              => masteriyo_rest_prepare_date_response( $coupon->get_expire_at() ),
			'author'                 => $author,
			'user'                   => UserResource::to_array( $user ),
		);

		/**
		 * Filter coupon data array resource.
		 *
		 * @since 2.8.3
		 *
		 * @param array $data Coupon data.
		 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
		 * @param string $context What the value is for. Valid values are view and edit.
		 */
		return apply_filters( 'masteriyo_zoom_resource_array', $data, $coupon, $context );
	}

	/**
	 * Get taxonomy terms if a coupon.
	 *
	 * @since 2.8.3
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param string $taxonomy Taxonomy slug.
	 *
	 * @return array
	 */
	protected static function get_taxonomy_terms( $coupon, $taxonomy = 'cat' ) {
		$terms = Utils::get_object_terms( $coupon->get_id(), 'coupon_' . $taxonomy );

		$terms = array_map(
			function ( $term ) {
				return array(
					'id'   => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
				);
			},
			$terms
		);

		$terms = 'difficulty' === $taxonomy ? array_shift( $terms ) : $terms;

		return $terms;
	}
}
