<?php
/**
 * Data accessors for email template storage.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use WC_Email;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Retrieves template and default payloads.
 */
trait WPMD_Email_Templates_Repository {

	/**
	 * Determine if custom templates are enabled.
	 *
	 * @return bool
	 */
	public static function is_enabled(): bool {
		return (bool) get_option( self::OPTION_ENABLE, true );
	}

	/**
	 * Retrieve labels for supported email types.
	 *
	 * @return array<string, string>
	 */
	public static function get_supported_email_types(): array {
		$types = array(
			'new_order'                 => esc_html__( 'New Order', 'mail-doctor' ),
			'customer_processing_order' => esc_html__( 'Processing Order', 'mail-doctor' ),
			'customer_completed_order'  => esc_html__( 'Completed Order', 'mail-doctor' ),
			'customer_invoice'          => esc_html__( 'Customer Invoice', 'mail-doctor' ),
			'customer_note'             => esc_html__( 'Customer Note', 'mail-doctor' ),
			'failed_order'              => esc_html__( 'Failed Order', 'mail-doctor' ),
			'customer_refunded_order'   => esc_html__( 'Refunded Order', 'mail-doctor' ),
			'customer_reset_password'   => esc_html__( 'Password Reset', 'mail-doctor' ),
		);

		if ( function_exists( 'WC' ) ) {
			$mailer = WC()->mailer();
			if ( $mailer ) {
				foreach ( $mailer->get_emails() as $email ) {
					if ( ! $email instanceof WC_Email ) {
						continue;
					}

					$types[ $email->id ] = $email->title ?? $email->get_title();
				}
			}
		}

		/**
		 * Filter the supported email types.
		 *
		 * @param array<string, string> $types Email type => label.
		 */
		return apply_filters( 'mail_doctor_supported_email_types', $types );
	}

	/**
	 * Load active template for an email type.
	 *
	 * @param string $email_type Email identifier.
	 * @return array<string, mixed>
	 */
	public static function get_template_data( string $email_type ): array {
		$email_type = sanitize_key( $email_type );
		if ( '' === $email_type ) {
			return array();
		}

		$cache_key = 'template:' . $email_type;

		$cached = wp_cache_get( $cache_key, self::CACHE_GROUP );
		if ( is_array( $cached ) ) {
			return $cached;
		}

		$template = self::get_active_custom_template( $email_type );

		if ( empty( $template ) ) {
			$template = self::get_default_template_data( $email_type );
		}

		if ( empty( $template ) ) {
			return array();
		}

		wp_cache_set( $cache_key, $template, self::CACHE_GROUP, HOUR_IN_SECONDS );

		return $template;
	}

	/**
	 * Fetch active custom template data.
	 *
	 * @param string $email_type Email identifier.
	 * @return array<string, mixed>
	 */
	protected static function get_active_custom_template( string $email_type ): array {
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for template lookup, result is cached.
		$posts = get_posts(
			array(
				'post_type'      => self::CPT,
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'meta_query'     => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for template lookup.
					array(
						'key'   => self::META_EMAIL_TYPE,
						'value' => $email_type,
					),
					array(
						'key'   => self::META_ACTIVE,
						'value' => '1',
					),
				),
				'orderby'        => 'modified',
				'order'          => 'DESC',
			)
		);

		if ( empty( $posts ) ) {
			return array();
		}

		$post_id = (int) $posts[0]->ID;

		return array(
			'post_id'    => $post_id,
			'source'     => 'custom',
			'is_active'  => true,
			'email_type' => $email_type,
			'subject'    => (string) get_post_meta( $post_id, self::META_SUBJECT, true ),
			'heading'    => (string) get_post_meta( $post_id, self::META_HEADING, true ),
			'html'       => (string) get_post_meta( $post_id, self::META_BODY, true ),
			'css'        => (string) get_post_meta( $post_id, self::META_CSS, true ),
		);
	}

	/**
	 * Retrieve default template data from bundled files.
	 *
	 * @param string $email_type Email identifier.
	 * @return array<string, mixed>
	 */
	public static function get_default_template_data( string $email_type ): array {
		$email_type = sanitize_key( $email_type );
		if ( '' === $email_type ) {
			return array();
		}

		$cache_key = 'default:' . $email_type;
		$cached    = wp_cache_get( $cache_key, self::CACHE_GROUP );
		if ( is_array( $cached ) ) {
			return $cached;
		}

		$file = MAIL_DOCTOR_PATH . 'templates/emails/' . $email_type . '.php';
		if ( ! file_exists( $file ) ) {
			return array();
		}

		global $mail_doctor_collecting_defaults;

		$previous_state           = $mail_doctor_collecting_defaults ?? false;
		$mail_doctor_collecting_defaults = true;

		$data = include $file;

		$mail_doctor_collecting_defaults = $previous_state;

		if ( ! is_array( $data ) ) {
			return array();
		}

		$data = wp_parse_args(
			$data,
			array(
				'post_id'    => 0,
				'source'     => 'default',
				'is_active'  => true,
				'email_type' => $email_type,
				'subject'    => '',
				'heading'    => '',
				'html'       => '',
				'css'        => '',
			)
		);

		wp_cache_set( $cache_key, $data, self::CACHE_GROUP, DAY_IN_SECONDS );

		return $data;
	}
}
