<?php
/**
 * Email Templates — drag-and-drop HTML email template builder.
 *
 * Provides CRUD operations for HTML email templates used in notifications
 * and campaigns. Templates support placeholders, responsive design, and
 * can be assigned to specific notification rules.
 *
 * @package Mersal_Notif
 */

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

class Mersal_Notif_Email_Templates {

	const OPTION = 'mnotif_email_templates';

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_action( 'wp_ajax_mnotif_save_email_template', array( $this, 'ajax_save' ) );
		add_action( 'wp_ajax_mnotif_delete_email_template', array( $this, 'ajax_delete' ) );
		add_action( 'wp_ajax_mnotif_test_email_template', array( $this, 'ajax_test' ) );
	}

	/**
	 * Get all templates.
	 *
	 * @return array<int,array>
	 */
	public static function get_all() {
		$templates = get_option( self::OPTION, array() );
		return is_array( $templates ) ? $templates : array();
	}

	/**
	 * Get a template by ID.
	 *
	 * @param int $id Template ID.
	 * @return array|null
	 */
	public static function get( $id ) {
		$templates = self::get_all();
		return $templates[ $id ] ?? null;
	}

	/**
	 * Save a template.
	 *
	 * @param array $data Template data.
	 * @return int Template ID.
	 */
	public static function save( array $data ) {
		$templates = self::get_all();
		$id        = isset( $data['id'] ) ? absint( $data['id'] ) : 0;

		if ( ! $id ) {
			$ids = array_keys( $templates );
			$id  = ( $ids ? (int) max( $ids ) : 0 ) + 1;
		}

		$templates[ $id ] = array(
			'id'           => $id,
			'name'         => sanitize_text_field( $data['name'] ?? '' ),
			'content_html' => wp_kses_post( $data['content_html'] ?? '' ),
			'content_json' => $data['content_json'] ?? '',
			'created_at'   => $templates[ $id ]['created_at'] ?? current_time( 'mysql' ),
			'updated_at'   => current_time( 'mysql' ),
		);

		update_option( self::OPTION, $templates, false );
		return $id;
	}

	/**
	 * Delete a template.
	 *
	 * @param int $id Template ID.
	 * @return bool
	 */
	public static function delete( $id ) {
		$templates = self::get_all();
		if ( isset( $templates[ $id ] ) ) {
			unset( $templates[ $id ] );
			update_option( self::OPTION, $templates, false );
			return true;
		}
		return false;
	}

	/**
	 * Wrap HTML content in a responsive email template.
	 *
	 * @param string $html Raw HTML content.
	 * @param string $site_name Site name.
	 * @return string Full HTML email.
	 */
	public static function wrap( $html, $site_name = '' ) {
		if ( '' === $site_name ) {
			$site_name = get_bloginfo( 'name' );
		}

		// If already a full HTML document, return as-is.
		if ( false !== strpos( $html, '<html' ) ) {
			return $html;
		}

		return '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>' . esc_html( $site_name ) . '</title>
</head>
<body style="margin:0;padding:0;background-color:#f4f4f4;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f4;padding:20px 0;">
<tr><td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff;border-radius:8px;overflow:hidden;max-width:600px;width:100%;">
<tr><td style="padding:32px;">
' . $html . '
</td></tr>
</table>
<table width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;">
<tr><td style="padding:16px;text-align:center;color:#999999;font-size:12px;">
' . esc_html( $site_name ) . '
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>';
	}

	/**
	 * Parse template placeholders.
	 *
	 * @param string $html HTML content.
	 * @param array  $data Placeholder data.
	 * @return string Parsed HTML.
	 */
	public static function parse( $html, $data = array() ) {
		$defaults = array(
			'{{user_name}}'         => '',
			'{{otp}}'               => '',
			'{{magic_link}}'        => '',
			'{{shop_name}}'         => get_bloginfo( 'name' ),
			'{{current_date_time}}' => wp_date( 'Y-m-d H:i' ),
			'{{site_link}}'         => home_url(),
		);
		$map = array_merge( $defaults, $data );
		return strtr( (string) $html, $map );
	}

	/**
	 * AJAX: Save template.
	 */
	public function ajax_save() {
		check_ajax_referer( 'mnotif_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'mersal-notifications' ) ) );
		}
		$name         = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );
		$content_html = wp_kses_post( wp_unslash( $_POST['content_html'] ?? '' ) );
		$content_json = wp_unslash( $_POST['content_json'] ?? '' );
		// Validate JSON if provided.
		if ( '' !== $content_json ) {
			$decoded = json_decode( $content_json, true );
			$content_json = ( json_last_error() === JSON_ERROR_NONE ) ? wp_json_encode( $decoded ) : '';
		}
		$id           = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;

		if ( '' === $name ) {
			wp_send_json_error( array( 'message' => __( 'Template name is required.', 'mersal-notifications' ) ) );
		}

		$saved_id = self::save( array(
			'id'           => $id,
			'name'         => $name,
			'content_html' => $content_html,
			'content_json' => $content_json,
		) );

		wp_send_json_success( array( 'id' => $saved_id ) );
	}

	/**
	 * AJAX: Delete template.
	 */
	public function ajax_delete() {
		check_ajax_referer( 'mnotif_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'mersal-notifications' ) ) );
		}
		$id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
		if ( $id && self::delete( $id ) ) {
			wp_send_json_success();
		}
		wp_send_json_error( array( 'message' => __( 'Template not found.', 'mersal-notifications' ) ) );
	}

	/**
	 * AJAX: Send test email with template.
	 */
	public function ajax_test() {
		check_ajax_referer( 'mnotif_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unauthorized.', 'mersal-notifications' ) ) );
		}
		$id      = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0;
		$email   = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
		$template = self::get( $id );

		if ( ! $template || ! is_email( $email ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid template or email.', 'mersal-notifications' ) ) );
		}

		$html  = self::parse( $template['content_html'] );
		$html  = self::wrap( $html );
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );
		$sent = wp_mail( $email, __( 'Test email template', 'mersal-notifications' ), $html, $headers );

		if ( $sent ) {
			wp_send_json_success( array( 'message' => __( 'Test email sent.', 'mersal-notifications' ) ) );
		}
		wp_send_json_error( array( 'message' => __( 'Failed to send.', 'mersal-notifications' ) ) );
	}
}
