<?php
/**
 * Maintenance helpers for email templates.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use MailDoctor\Email\CacheService;
use MailDoctor\Email\Template;
use MailDoctor\Email\TemplateRepository;

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

/**
 * Cache and lifecycle utilities for templates.
 */
trait WPMD_Email_Templates_Maintenance {

	/**
	 * Clear cached template data for a specific type.
	 *
	 * @param string $email_type Email identifier.
	 * @return void
	 */
	public static function clear_template_cache( string $email_type ): void {
		$email_type = sanitize_key( $email_type );

		wp_cache_delete( 'template:' . $email_type, self::CACHE_GROUP );
		wp_cache_delete( 'default:' . $email_type, self::CACHE_GROUP );
		self::$template_repository = null;
		self::$override_resolver   = null;
		\MailDoctor\Email\TemplateRepository::flush_cache();

		$template_data = self::get_template_data( $email_type );

		if ( ! empty( $template_data['id'] ) ) {
			CacheService::invalidate_template( (string) $template_data['id'] );
		}

		if ( ! empty( $template_data['post_id'] ) ) {
			CacheService::invalidate_template( (string) $template_data['post_id'] );
		}

		CacheService::invalidate_template( 'default-' . $email_type );
	}

	/**
	 * Flush all cached template data.
	 *
	 * @param mixed $old_value Previous option value.
	 * @param mixed $value     New option value.
	 * @return void
	 */
	public static function flush_template_cache( $old_value = null, $value = null ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
		foreach ( array_keys( self::get_supported_email_types() ) as $email_type ) {
			self::clear_template_cache( $email_type );
		}
		self::$template_repository = null;
		self::$override_resolver   = null;
		\MailDoctor\Email\TemplateRepository::flush_cache();
		CacheService::invalidate_all();
	}

	/**
	 * Seed default templates for every supported email type.
	 *
	 * @return void
	 */
	public static function seed_defaults(): void {
		foreach ( self::get_supported_email_types() as $email_type => $label ) {
			$data = self::get_default_template_data( $email_type );

			if ( empty( $data ) ) {
				continue;
			}

			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for template existence check during seeding.
			$existing = get_posts(
				array(
					'post_type'      => self::CPT,
					'post_status'    => 'any',
					'posts_per_page' => 1,
					'meta_query'     => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
						array(
							'key'   => self::META_EMAIL_TYPE,
							'value' => $email_type,
						),
					),
				)
			);

			if ( ! empty( $existing ) ) {
				continue;
			}

			$post_id = wp_insert_post(
				array(
					'post_type'   => self::CPT,
					'post_status' => 'publish',
					'post_title'  => $label,
				)
			);

			if ( is_wp_error( $post_id ) || ! $post_id ) {
				continue;
			}

			update_post_meta( $post_id, self::META_EMAIL_TYPE, $email_type );
			update_post_meta( $post_id, self::META_SUBJECT, $data['subject'] ?? '' );
			update_post_meta( $post_id, self::META_HEADING, $data['heading'] ?? '' );
			update_post_meta( $post_id, self::META_BODY, $data['html'] ?? '' );
			update_post_meta( $post_id, self::META_CSS, $data['css'] ?? '' );
			update_post_meta( $post_id, self::META_ACTIVE, 1 );
		}
	}

	/**
	 * Reset a template to plugin defaults.
	 *
	 * @param string $email_type Email identifier.
	 * @return bool
	 */
	public static function reset_to_defaults( string $email_type ): bool {
		$email_type = sanitize_key( $email_type );
		$data       = self::get_default_template_data( $email_type );

		if ( empty( $data ) ) {
			return false;
		}

		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for template lookup during reset.
		$templates = get_posts(
			array(
				'post_type'      => self::CPT,
				'post_status'    => 'any',
				'posts_per_page' => 1,
				'meta_query'     => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					array(
						'key'   => self::META_EMAIL_TYPE,
						'value' => $email_type,
					),
				),
			)
		);

		if ( empty( $templates ) ) {
			return false;
		}

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

		update_post_meta( $post_id, self::META_SUBJECT, $data['subject'] ?? '' );
		update_post_meta( $post_id, self::META_HEADING, $data['heading'] ?? '' );
		update_post_meta( $post_id, self::META_BODY, $data['html'] ?? '' );
		update_post_meta( $post_id, self::META_CSS, $data['css'] ?? '' );
		update_post_meta( $post_id, self::META_ACTIVE, 1 );

		$editor_mode = (string) get_post_meta( $post_id, '_mail_doctor_editor_mode', true ) ?: 'code';

		( new TemplateRepository() )->record_history(
			new Template(
				$email_type,
				array(
					'id'          => (string) $post_id,
					'post_id'     => $post_id,
					'email_type'  => $email_type,
					'subject'     => $data['subject'] ?? '',
					'heading'     => $data['heading'] ?? '',
					'html'        => $data['html'] ?? '',
					'css'         => $data['css'] ?? '',
					'source'      => 'default',
					'is_active'   => true,
					'editor_mode' => $editor_mode,
				)
			),
			array(
				'post_id'     => $post_id,
				'editor_mode' => $editor_mode,
				'locale'      => get_locale(),
			)
		);

		self::clear_template_cache( $email_type );
		CacheService::invalidate_template( (string) $post_id );
		CacheService::invalidate_template( 'default-' . $email_type );

		return true;
	}

	/**
	 * Plugin activation hook.
	 *
	 * @return void
	 */
	public static function activate(): void {
		self::register_content_types();
		self::ensure_default_option();
		self::seed_defaults();
		flush_rewrite_rules();
	}
}
