<?php
/**
 * Email Templates Handler for WAWP.
 *
 * @package automation-web-platform
 */

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

/**
 * WAWP_Email_Templates Class.
 * Handles creation, management, and preview of email templates.
 */
class WAWP_Email_Templates {
	use WAWP_Security_Trait;
	use WAWP_Settings_Handler;

	/**
	 * Singleton instance.
	 *
	 * @var WAWP_Email_Templates
	 */
	private static $instance = null;

	/**
	 * Singleton instance.
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {}

	/**
	 * Get the database table name from manager.
	 *
	 * @return string
	 */
	private function get_table() {
		return WAWP()->db->tables['email_templates'];
	}

	/**
	 * AJAX: Save template.
	 */
	public function ajax_save_email_template() {
		check_ajax_referer( 'wawp_dashboard_nonce', 'security' );
		$this->check_permissions( 'wawp_dashboard_nonce', 'security' );
		$result = $this->handle_save_template( $_POST );
		if ( $result['success'] ) {
			$this->send_success( $result['message'], isset( $result['data'] ) ? $result['data'] : array() );
		} else {
			$this->send_error( $result['message'] );
		}
	}

	/**
	 * AJAX: Get templates list.
	 */
	public function ajax_get_email_templates() {
		$this->check_permissions( 'wawp_dashboard_nonce', 'security' );
		$result = $this->handle_get_templates();
		$this->send_success( '', array( 'templates' => $result ) );
	}

	/**
	 * AJAX: Delete template.
	 */
	public function ajax_delete_email_template() {
		check_ajax_referer( 'wawp_dashboard_nonce', 'security' );
		$this->check_permissions( 'wawp_dashboard_nonce', 'security' );
		$id     = isset( $_POST['id'] ) ? intval( wp_unslash( $_POST['id'] ) ) : 0;
		$result = $this->handle_delete_template( $id );
		if ( $result['success'] ) {
			$this->send_success();
		} else {
			$this->send_error( $result['message'] );
		}
	}

	/**
	 * Handle sending a test email.
	 *
	 * @param array $data Test data.
	 * @return array
	 */
	public function handle_send_test_email( $data ) {
		$test_email   = isset( $data['email'] ) ? sanitize_email( wp_unslash( $data['email'] ) ) : '';
		$content_html = isset( $data['content_html'] ) ? wp_unslash( $data['content_html'] ) : '';
		$name         = isset( $data['name'] ) ? sanitize_text_field( wp_unslash( $data['name'] ) ) : 'Test Template';

		if ( empty( $test_email ) ) {
			return array(
				'success' => false,
				'message' => __( 'Test email address is required', 'automation-web-platform' ),
			);
		}

		if ( empty( $content_html ) ) {
			return array(
				'success' => false,
				'message' => __( 'Template content is empty', 'automation-web-platform' ),
			);
		}

		// Process placeholders for test.
		$placeholders = array(
			'{{user_name}}'         => 'Test User',
			'{{otp}}'               => '123456',
			'{{wawp_login_link}}'   => site_url( '/?wawp_magic_token=test_token' ),
			'{{magic_link}}'        => site_url( '/?wawp_magic_token=test_token' ),
			'{{shop_name}}'         => get_bloginfo( 'name' ),
			'{{current_date_time}}' => gmdate( 'Y-m-d H:i:s' ),
			'{{site_link}}'         => site_url(),
		);

		foreach ( $placeholders as $key => $val ) {
			$content_html = str_replace( $key, $val, $content_html );
		}

		$subject = '[TEST] ' . $name;
		if ( class_exists( 'WAWP_Email_Inliner' ) ) {
			$content_html = WAWP_Email_Inliner::inline( $content_html );
		}

		$sent = WAWP_Messaging_Service::get_instance()->send(
			$test_email,
			array(
				'channel'          => 'email',
				'subject'          => $subject,
				'message'          => $content_html,
				'context'          => __( 'Email Template - Test Send', 'automation-web-platform' ),
				'send_timing'      => 'instant',
				'is_html_template' => true,
			)
		);

		if ( $sent ) {
			return array(
				'success' => true,
				// translators: %s is the recipient email address.
				'message' => sprintf( __( 'Test email sent successfully to %s', 'automation-web-platform' ), $test_email ),
			);
		}

		return array(
			'success' => false,
			'message' => __( 'Failed to send test email. Check logs for details.', 'automation-web-platform' ),
		);
	}

	/**
	 * Save or update template.
	 *
	 * @param array $data Template data.
	 * @return array
	 */
	public function handle_save_template( $data ) {
		global $wpdb;
		$table        = $this->get_table();
		$id           = isset( $data['id'] ) ? intval( $data['id'] ) : 0;
		$name         = isset( $data['name'] ) ? sanitize_text_field( $data['name'] ) : '';
		$content_json = isset( $data['content_json'] ) ? $data['content_json'] : '';
		$content_html = isset( $data['content_html'] ) ? $data['content_html'] : '';

		if ( empty( $name ) ) {
			return array(
				'success' => false,
				'message' => __( 'Template name is required', 'automation-web-platform' ),
			);
		}

		$row_data = array(
			'name'         => $name,
			'content_json' => $content_json,
			'content_html' => $content_html,
			'updated_at'   => current_time( 'mysql' ),
		);

		if ( $id > 0 ) {
			WAWP()->db->update_row( 'email_templates', $row_data, array( 'id' => $id ) );
		} else {
			$row_data['created_at'] = current_time( 'mysql' );
			$id                     = WAWP()->db->insert( 'email_templates', $row_data );
		}

		$this->clear_caches( $id );

		return array(
			'success' => true,
			'message' => __( 'Template saved successfully', 'automation-web-platform' ),
			'data'    => array( 'id' => $id ),
		);
	}

	/**
	 * Get all templates.
	 *
	 * @return array
	 */
	public function handle_get_templates() {
		$cache_key = 'wawp_email_templates_list_v2';
		$results   = wp_cache_get( $cache_key, 'wawp_email' );

		if ( false === $results ) {
			global $wpdb;
			$table   = $this->get_table();
			$results = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT id, name, created_at, updated_at, content_json, content_html FROM %i ORDER BY id DESC', $table ), $cache_key, 'wawp_email', HOUR_IN_SECONDS );
		}

		return $results ? $results : array();
	}

	/**
	 * Get single template.
	 *
	 * @param int $id Template ID.
	 * @return array
	 */
	public function handle_get_template( $id ) {
		if ( ! $id ) {
			return array(
				'success' => false,
				'message' => __( 'Invalid template ID', 'automation-web-platform' ),
			);
		}

		$cache_key = 'wawp_email_template_' . $id;
		$template  = wp_cache_get( $cache_key, 'wawp_email' );

		if ( false === $template ) {
			global $wpdb;
			$table    = $this->get_table();
			$template = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ), $cache_key, 'wawp_email', HOUR_IN_SECONDS );
			$template = ! empty( $template ) ? (object) $template[0] : null;
		}

		if ( ! $template ) {
			return array(
				'success' => false,
				'message' => __( 'Template not found', 'automation-web-platform' ),
			);
		}

		return array(
			'success' => true,
			'data'    => $template,
		);
	}

	/**
	 * Delete template.
	 *
	 * @param int $id Template ID.
	 * @return array
	 */
	public function handle_delete_template( $id ) {
		if ( ! $id ) {
			return array(
				'success' => false,
				'message' => __( 'Invalid template ID', 'automation-web-platform' ),
			);
		}

		WAWP()->db->delete_row( 'email_templates', array( 'id' => $id ) );

		$this->clear_caches( $id );

		return array( 'success' => true );
	}

	/**
	 * Clear relevant caches.
	 *
	 * @param int $id Template ID.
	 */
	private function clear_caches( $id = 0 ) {
		wp_cache_delete( 'wawp_email_templates_list_v2', 'wawp_email' );
		wp_cache_delete( 'wawp_email_templates_list_v2', 'wawp_notif' );
		wp_cache_delete( 'wawp_email_templates_id_name', 'wawp_notif' );
		if ( $id ) {
			wp_cache_delete( 'wawp_email_template_' . $id, 'wawp_email' );
		}
	}

	/**
	 * Data for React UI.
	 */
	public function get_react_settings_data() {
		$registry_defaults = WAWP_Settings_Registry::get_defaults();
		$db_key            = WAWP_Settings_Registry::AUTH_EMAIL_DOMAINS;
		$default           = $registry_defaults[ $db_key ] ?? array();

		$val = $this->get_wawp_setting( $db_key, $default );

		// If it's a JSON string or otherwise stored, decode or parse it.
		$val = $this->from_db( $val );
		if ( is_string( $val ) ) {
			$val = json_decode( $val, true );
		}
		if ( ! is_array( $val ) ) {
			$val = $default;
		}

		$option_names = array(
			'emailDomains' => $db_key,
		);

		$mapped_options = array(
			'emailDomains' => $val,
			$db_key        => $val,
		);

		return array(
			'options'     => $mapped_options,
			'optionNames' => $option_names,
			'i18n'        => array(
				'title'         => __( 'Email Templates', 'automation-web-platform' ),
				'subtitle'      => __( 'Design professional, high-converting email templates using a drag-and-drop builder.', 'automation-web-platform' ),
				'settingsSaved' => __( 'Email domain suggestions saved successfully!', 'automation-web-platform' ),
			),
		);
	}
}
