<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Display the template editor page.
 *
 * Renders the email template editor interface with GrapesJS editor,
 * template selection, and saving functionality.
 *
 * @since 1.0.0
 */
function x4email_lite_template_editor_page() {
	// Get all available email templates.
	$template_dir   = plugin_dir_path( __FILE__ ) . '../templates/';
	$template_files = glob( $template_dir . '*.php' );
	$templates      = array();

	foreach ( $template_files as $template_file ) {
		$template_name               = basename( $template_file, '.php' );
		$templates[ $template_name ] = $template_name;
	}

	// Enqueue WordPress core scripts and styles first.
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'jquery-ui-core' );
	wp_enqueue_script( 'jquery-ui-dialog' );
	wp_enqueue_style( 'wp-jquery-ui-dialog' );

	// Enqueue media scripts.
	wp_enqueue_media();

	// Enqueue GrapesJS and its dependencies.
	wp_enqueue_script( 'grapesjs', esc_url( plugins_url( 'assets/js/grapes.min.js', dirname( __DIR__ ) ) ), array( 'jquery' ), '0.21.2', true );
	wp_enqueue_style( 'grapesjs-css', esc_url( plugins_url( 'assets/css/grapes.min.css', dirname( __DIR__ ) ) ), array(), '0.21.2' );
	wp_enqueue_style( 'font-awesome', esc_url( plugins_url( 'assets/css/font-awesome.min.css', dirname( __DIR__ ) ) ), array(), '5.15.4' );

	// Add GrapesJS plugins.
	wp_enqueue_script( 'grapesjs-preset-newsletter', esc_url( plugins_url( 'assets/js/grapesjs-preset-newsletter.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-plugin-export', esc_url( plugins_url( 'assets/js/grapesjs-plugin-export.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-style-bg', esc_url( plugins_url( 'assets/js/grapesjs-style-bg.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-style-filter', esc_url( plugins_url( 'assets/js/grapesjs-style-filter.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-custom-code', esc_url( plugins_url( 'assets/js/grapesjs-custom-code.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-parser-postcss', esc_url( plugins_url( 'assets/js/grapesjs-parser-postcss.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-blocks-basic', esc_url( plugins_url( 'assets/js/grapesjs-blocks-basic.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );
	wp_enqueue_script( 'grapesjs-studio-sdk-plugins', esc_url( plugins_url( 'assets/js/grapesjs-studio-sdk-plugins.min.js', dirname( __DIR__ ) ) ), array( 'grapesjs' ), '1.0.0', true );

	// Enqueue our custom files.
	wp_enqueue_style( 'x4email-template-editor', esc_url( plugins_url( 'assets/css/template-editor.css', dirname( __DIR__ ) ) ), array(), X4EMAIL_LITE_VER );
	wp_enqueue_script( 'x4email-template-editor', esc_url( plugins_url( 'assets/js/template-editor.js', dirname( __DIR__ ) ) ), array( 'grapesjs', 'jquery', 'media-views' ), X4EMAIL_LITE_VER, true );

	// Pass template data to JavaScript.
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin page parameter for template loading, no form processing.
	$initial_template = isset( $_GET['template'] ) ? sanitize_text_field( wp_unslash( $_GET['template'] ) ) : '';

	wp_localize_script(
		'x4email-template-editor',
		'x4emailEditor',
		array(
			'ajaxUrl'              => admin_url( 'admin-ajax.php' ),
			'nonce'                => wp_create_nonce( 'x4email_editor_nonce' ),
			'templates'            => x4email_get_template_list(),
			'mediaFrameTitle'      => __( 'Select or Upload Image', 'x4email-lite' ),
			'mediaFrameButtonText' => __( 'Use this image', 'x4email-lite' ),
			'siteLogo'             => get_custom_logo() ? wp_get_attachment_url( get_theme_mod( 'custom_logo' ) ) : plugins_url( 'assets/img/placeholder-image.png', dirname( __DIR__ ) ),
			'pluginUrl'            => plugin_dir_url( dirname( __DIR__ ) ),
			'initialTemplate'      => $initial_template,
		)
	);
	?>
	<div class="x4email-editor-wrapper">
		<div class="x4email-editor-container">
			<div class="x4email-main">
				<div class="x4email-toolbar">
					<div style="display: flex; align-items: center; gap: 10px;">
						<button id="save-template">Save Template</button>
						<button id="toggle-fullscreen" title="Toggle Fullscreen">
							<i class="fas fa-expand"></i>
						</button>
					</div>
					<div class="template-selector">
						<select id="template-select" class="regular-text">
							<option value=""><?php echo esc_html__( 'Select a template...', 'x4email-lite' ); ?></option>
							
							<!-- Admin Templates -->
							<optgroup label="<?php echo esc_html__( 'Admin Templates', 'x4email-lite' ); ?>">
								<?php
								$admin_templates = array(
									'admin-cancelled-order' => 'Cancelled Order',
									'admin-new-order'    => 'New Order',
									'admin-failed-order' => 'Failed Order',
								);
								foreach ( $admin_templates as $template => $display_name ) {
									if ( isset( $templates[ $template ] ) ) {
										echo '<option value="' . esc_attr( $template ) . '" data-cat="woo-cat">' . esc_html( $display_name ) . '</option>';
									} else {
										echo '<option value="' . esc_attr( $template ) . '" data-cat="security-cat">' . esc_html( $display_name ) . ' - 🔒 Locked</option>';
									}
								}
								?>
							</optgroup>

							<!-- Customer Templates -->
							<optgroup label="<?php echo esc_html__( 'Customer Templates', 'x4email-lite' ); ?>">
								<?php
								$customer_templates = array(
									'customer-reset-password' => 'Password Reset',
									'customer-refunded-order' => 'Order Refunded',
									'customer-processing-order' => 'Order Processing',
									'customer-on-hold-order' => 'Order On Hold',
									'customer-note'        => 'Order Note',
									'customer-new-account' => 'New Account',
									'customer-new-account-blocks' => 'New Account (Blocks)',
									'customer-invoice'     => 'Order Invoice',
									'customer-failed-order' => 'Failed Order',
									'customer-completed-order' => 'Order Completed',
								);
								foreach ( $customer_templates as $template => $display_name ) {
									if ( isset( $templates[ $template ] ) ) {
										echo '<option value="' . esc_attr( $template ) . '" data-cat="woo-cat">' . esc_html( $display_name ) . '</option>';
									} else {
										echo '<option value="' . esc_attr( $template ) . '" data-cat="security-cat">' . esc_html( $display_name ) . ' - 🔒 Locked</option>';
									}
								}
								?>
							</optgroup>

							<!-- Security Templates -->
							<optgroup label="<?php echo esc_html__( 'Security Templates', 'x4email-lite' ); ?>">
								<?php
								$security_templates = array(
									'admin-2fa-pin' => '2FA PIN',
									'admin-login-notification' => 'Login Notification',
								);
								foreach ( $security_templates as $template => $display_name ) {
									if ( isset( $templates[ $template ] ) ) {
										echo '<option value="' . esc_attr( $template ) . '" data-cat="security-cat">' . esc_html( $display_name ) . '</option>';
									} else {
										echo '<option value="' . esc_attr( $template ) . '" data-cat="security-cat">' . esc_html( $display_name ) . ' - 🔒 Locked</option>';
									}
								}
								?>
							</optgroup>
						</select>
					</div>
				</div>
				<div id="gjs"></div>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Get the custom templates directory path.
 *
 * Returns the absolute path to the directory where custom email templates
 * are stored within the plugin structure.
 *
 * @since 1.0.0
 *
 * @return string The custom templates directory path.
 */
function x4email_get_custom_templates_dir() {
	$upload_dir = wp_upload_dir();
	$custom_dir = $upload_dir['basedir'] . '/x4email_lt_tmplt';

	// Create directory if it doesn't exist.
	if ( ! file_exists( $custom_dir ) ) {
		wp_mkdir_p( $custom_dir );
	}

	return $custom_dir;
}

/**
 * Get list of available email templates.
 *
 * Scans both the plugin's default templates directory and the custom
 * templates directory to return an array of available templates.
 *
 * @since 1.0.0
 *
 * @return array Array of template names and their display names.
 */
function x4email_get_template_list() {
	// Get default templates from plugin directory.
	$default_template_dir   = plugin_dir_path( __FILE__ ) . '../templates/';
	$default_template_files = glob( $default_template_dir . '*.php' );

	// Get custom templates from uploads directory.
	$custom_template_dir   = x4email_get_custom_templates_dir();
	$custom_template_files = glob( $custom_template_dir . '/*.php' );

	$templates = array();

	// Process default templates.
	foreach ( $default_template_files as $template_file ) {
		$template_name    = basename( $template_file, '.php' );
		$template_content = file_get_contents( $template_file );

		// Extract CSS from template if it exists.
		$css = '';
		if ( preg_match( '/<style[^>]*>(.*?)<\/style>/s', $template_content, $matches ) ) {
			$css = $matches[1];
		}

		$templates[ $template_name ] = array(
			'name'      => $template_name,
			'content'   => $template_content,
			'css'       => $css,
			'is_custom' => false,
		);
	}

	// Process custom templates.
	foreach ( $custom_template_files as $template_file ) {
		$template_name    = basename( $template_file, '.php' );
		$template_content = file_get_contents( $template_file );

		// Extract CSS from template if it exists.
		$css = '';
		if ( preg_match( '/<style[^>]*>(.*?)<\/style>/s', $template_content, $matches ) ) {
			$css = $matches[1];
		}

		$templates[ $template_name ] = array(
			'name'      => $template_name,
			'content'   => $template_content,
			'css'       => $css,
			'is_custom' => true,
		);
	}

	return $templates;
}

/**
 * Handle AJAX request to load template content.
 *
 * Loads template content, CSS, and metadata for the template editor.
 * Verifies user permissions and nonce before processing.
 *
 * @since 1.0.0
 */
function x4email_load_template_ajax() {
	// Check user capabilities first.
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'You do not have permission to perform this action.', 'x4email-lite' ),
			)
		);
		return;
	}

	check_ajax_referer( 'x4email_editor_nonce', 'nonce' );

	if ( ! isset( $_POST['template_name'] ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'Template name is required.', 'x4email-lite' ),
			)
		);
		wp_die();
	}

	$template_name = sanitize_text_field( wp_unslash( $_POST['template_name'] ) );

	// Validate template name.
	if ( ! preg_match( '/^[a-zA-Z0-9_\-]+$/', $template_name ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'Invalid template name.', 'x4email-lite' ),
			)
		);
		wp_die();
	}

	$custom_template_dir  = x4email_get_custom_templates_dir();
	$custom_template_file = $custom_template_dir . '/' . $template_name . '.php';

	if ( file_exists( $custom_template_file ) &&
		strpos( realpath( $custom_template_file ), realpath( $custom_template_dir ) ) === 0 ) {
		$content = file_get_contents( $custom_template_file );
	} else {
		$default_template_dir  = plugin_dir_path( __FILE__ ) . '../templates/';
		$default_template_file = $default_template_dir . $template_name . '.php';

		if ( file_exists( $default_template_file ) &&
			strpos( realpath( $default_template_file ), realpath( $default_template_dir ) ) === 0 ) {
			$content = file_get_contents( $default_template_file );
		} else {
			wp_send_json_error(
				array(
					'message'  => __( 'Buy Pro to unlock this template', 'x4email-lite' ),
					'redirect' => admin_url( 'admin.php?page=x4email-template-editor&template=admin-new-order' ),
				)
			);
			die();
		}
	}

	$css = '';
	if ( preg_match( '/<style[^>]*>(.*?)<\/style>/s', $content, $matches ) ) {
		$css = $matches[1];
	}

	wp_send_json_success(
		array(
			'content' => $content,
			'css'     => $css,
		)
	);

	wp_die();
}
add_action( 'wp_ajax_x4email_load_template', 'x4email_load_template_ajax' );

/**
 * Handle AJAX request to save template content.
 *
 * Saves template content and CSS to a file in the custom templates directory.
 * Verifies user permissions and nonce before processing.
 *
 * @since 1.0.0
 */
function x4email_save_template_ajax() {
	// Check user capabilities first.
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'You do not have permission to perform this action.', 'x4email-lite' ),
			)
		);
		return;
	}

	check_ajax_referer( 'x4email_editor_nonce', 'nonce' );

	// Validate required fields.
	if ( ! isset( $_POST['template_name'] ) || ! isset( $_POST['content'] ) || ! isset( $_POST['css'] ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'Required fields are missing.', 'x4email-lite' ),
			)
		);
		return;
	}

	$template_name = sanitize_text_field( wp_unslash( $_POST['template_name'] ) );

	// Validate template name format.
	if ( ! preg_match( '/^[a-zA-Z0-9_\-]+$/', $template_name ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'Invalid template name format.', 'x4email-lite' ),
			)
		);
		return;
	}

	// Sanitize inputs while preserving functionality for email templates.
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Content needs stripslashes for email template functionality.
	$content = stripslashes( wp_unslash( $_POST['content'] ) ); // Remove slashes as needed for templates
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- CSS needs stripslashes for email template functionality.
	$css = stripslashes( wp_unslash( $_POST['css'] ) ); // Remove slashes as needed for templates

	// Additional validation.
	if ( empty( $template_name ) ) {
		wp_send_json_error(
			array(
				'message' => __( 'Template name cannot be empty.', 'x4email-lite' ),
			)
		);
		return;
	}

	// Basic validation without breaking functionality.
	if ( strlen( $content ) > 2000000 ) { // 2MB limit (increased)
		wp_send_json_error(
			array(
				'message' => __( 'Content is too large.', 'x4email-lite' ),
			)
		);
		return;
	}

	// Combine HTML and CSS.
	$full_content = "<!DOCTYPE html>\n<html>\n<head>\n<style>\n" . $css . "\n</style>\n</head>\n<body>\n" . $content . "\n</body>\n</html>";

	// Save to custom templates directory only.
	$custom_template_dir = x4email_get_custom_templates_dir();
	$template_file       = $custom_template_dir . '/' . $template_name . '.php';

	// Save to file.
	$file_result = file_put_contents( $template_file, $full_content );

	if ( $file_result === false ) {
		wp_send_json_error(
			array(
				'message' => __( 'Failed to save template file', 'x4email-lite' ),
			)
		);
		return;
	}

	// Clear any caching.
	wp_cache_flush();

	wp_send_json_success(
		array(
			'message' => __( 'Template saved successfully', 'x4email-lite' ),
		)
	);
}
add_action( 'wp_ajax_x4email_save_template', 'x4email_save_template_ajax' );
