<?php
/**
 * Postomatic Plugin - Easy Digital Downloads Product Source.
 *
 * PHP Version 5.6
 *
 * @package  Postomatic
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.3.0
 */

namespace Postomatic\Api;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Product_Source_Easy_Digital_Downloads.
 *
 * Reads products ("Downloads") from Easy Digital Downloads using its own
 * documented API (`EDD_Download`, `edd_price()`, `edd_get_download_final_price()`)
 * against the `download` post type that EDD itself registers.
 *
 * @since 1.3.0
 */
class Product_Source_Easy_Digital_Downloads extends Product_Source_Abstract {

	const PLATFORM_KEY = 'easy_digital_downloads';
	const POST_TYPE    = 'download';

	/**
	 * {@inheritDoc}
	 */
	public static function is_active(): bool {
		// EDD defines this constant in its main plugin file and the
		// EDD_Download class is the documented way to interact with a
		// single product ("download").
		return defined( 'EDD_VERSION' ) && class_exists( 'EDD_Download' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_platform_key(): string {
		return self::PLATFORM_KEY;
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_platform_label(): string {
		return 'Easy Digital Downloads';
	}

	/**
	 * {@inheritDoc}
	 */
	public function has_products(): bool {
		if ( ! self::is_active() ) {
			return false;
		}

		$ids = get_posts(
			array(
				'post_type'      => self::POST_TYPE,
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'fields'         => 'ids',
				'no_found_rows'  => true,
			)
		);

		return ! empty( $ids );
	}

	/**
	 * {@inheritDoc}
	 *
	 * @param string $search   Optional search term to filter by product name.
	 * @param int    $page     Page number (1-indexed).
	 * @param int    $per_page Number of products per page.
	 */
	public function get_products( string $search = '', int $page = 1, int $per_page = 20 ): array {
		if ( ! self::is_active() ) {
			return $this->empty_result( $page, $per_page );
		}

		$args = array(
			'post_type'      => self::POST_TYPE,
			'post_status'    => 'publish',
			'posts_per_page' => $per_page,
			'paged'          => $page,
		);

		if ( '' !== $search ) {
			$args['s'] = $search;
		}

		$query = new \WP_Query( $args );

		$total = (int) $query->found_posts;

		$products = array();

		if ( $query->have_posts() ) {
			foreach ( $query->posts as $post ) {
				$products[] = $this->format_product( new \EDD_Download( $post->ID ) );
			}
		}

		wp_reset_postdata();

		return array(
			'products'   => $products,
			'pagination' => $this->build_pagination( $total, $page, $per_page ),
		);
	}

	/**
	 * Normalize a single EDD_Download into Postomatic's shared product shape.
	 *
	 * @param \EDD_Download $download EDD download object.
	 *
	 * @return array<string, mixed>
	 */
	private function format_product( $download ): array {
		$product_id = $download->ID;

		$main_image_id  = get_post_thumbnail_id( $product_id );
		$main_image_url = $main_image_id ? wp_get_attachment_url( $main_image_id ) : '';
		$large_image    = $main_image_id ? wp_get_attachment_image_src( $main_image_id, 'large' ) : false;

		$price      = function_exists( 'edd_get_download_price' ) ? edd_get_download_price( $product_id ) : $download->get_price();
		$price_html = function_exists( 'edd_price' ) ? edd_price( $product_id, false ) : (string) $price;

		$categories = wp_get_post_terms( $product_id, 'download_category', array( 'fields' => 'names' ) );
		$tags       = wp_get_post_terms( $product_id, 'download_tag', array( 'fields' => 'names' ) );

		$product_meta = array(
			'id'                 => $product_id,
			'platform'           => self::PLATFORM_KEY,
			'name'               => $download->post_title,
			'sku'                => $download->get_sku(),
			'price'              => $price,
			'regular_price'      => $price,
			'sale_price'         => '',
			'price_html'         => $price_html,
			'on_sale'            => false,
			'stock_status'       => 'instock',
			'stock_quantity'     => '',
			'short_description'  => has_excerpt( $product_id ) ? get_the_excerpt( $product_id ) : '',
			'description'        => $download->post_content,
			'permalink'          => get_permalink( $product_id ),
			'categories'         => is_wp_error( $categories ) ? array() : $categories,
			'tags'               => is_wp_error( $tags ) ? array() : $tags,
			'attributes'         => array(),
			'dimensions'         => array(
				'length' => '',
				'width'  => '',
				'height' => '',
			),
			'weight'             => '',
			'average_rating'     => '',
			'review_count'       => '',
			'image_ids'          => $main_image_id ? array( $main_image_id ) : array(),
			'image_urls'         => $main_image_url ? array( $main_image_url ) : array(),
			'article_image_ids'  => array(),
			'article_image_urls' => array(),
			'main_image'         => $main_image_url,
			'main_image_large'   => $large_image ? $large_image[0] : $main_image_url,
			'related_products'   => array(),
		);

		return $this->build_list_item(
			$product_id,
			$download->post_title,
			$price_html,
			has_excerpt( $product_id ) ? get_the_excerpt( $product_id ) : '',
			get_permalink( $product_id ),
			$main_image_url,
			$product_meta
		);
	}
}
