<?php
/**
 * Design repository for retrieving PDF designs.
 *
 * @package PDFDraft
 */

namespace PDFDraft\Repositories;

use PDFDraft\Contracts\Repositories\DesignRepositoryInterface;

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

/**
 * Repository for querying PDF design posts.
 */
class DesignRepository implements DesignRepositoryInterface {

	/**
	 * Post type identifier.
	 *
	 * @var string
	 */
	private const POST_TYPE = 'pdfdraft-design';

	/**
	 * Find a design by its post ID.
	 *
	 * @param int $id Post ID.
	 * @return array|null Parsed design content or null if not found.
	 */
	public function findById( int $id ): ?array {
		$post = get_post( $id );

		if ( ! $post || self::POST_TYPE !== $post->post_type ) {
			return null;
		}

		return $this->parseContent( $post->post_content );
	}

	/**
	 * Find a design by its slug.
	 *
	 * @param string $slug Post slug.
	 * @return array|null Parsed design content or null if not found.
	 */
	public function findBySlug( string $slug ): ?array {
		$query = new \WP_Query(
			array(
				'name'           => $slug,
				'post_type'      => self::POST_TYPE,
				'posts_per_page' => 1,
				'post_status'    => 'publish',
			)
		);

		if ( ! $query->have_posts() ) {
			return null;
		}

		return $this->parseContent( current( $query->posts )->post_content );
	}

	/**
	 * Parse content from JSON string.
	 *
	 * @param string $content JSON content string.
	 * @return array Parsed content array.
	 */
	private function parseContent( string $content = '' ): array {
		$content = json_decode( $content, true );

		if ( JSON_ERROR_NONE !== json_last_error() ) {
			return array();
		}

		return is_array( $content ) ? $content : array();
	}
}
