<?php
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register custom post type for email templates.
 *
 * Registers the 'x4email_lt_tmplt' custom post type to store email templates
 * with support for title, editor, and custom fields.
 *
 * @since 1.0.0
 */
function x4email_register_template_post_type() {
	$labels = array(
		'name'               => __( 'Templates', 'x4email-lite' ),
		'singular_name'      => __( 'Template', 'x4email-lite' ),
		'menu_name'          => __( 'Templates', 'x4email-lite' ),
		'name_admin_bar'     => __( 'Template', 'x4email-lite' ),
		'add_new'            => __( 'Add New', 'x4email-lite' ),
		'add_new_item'       => __( 'Add New Template', 'x4email-lite' ),
		'edit_item'          => __( 'Edit Template', 'x4email-lite' ),
		'new_item'           => __( 'New Template', 'x4email-lite' ),
		'view_item'          => __( 'View Template', 'x4email-lite' ),
		'all_items'          => __( 'All Templates', 'x4email-lite' ),
		'search_items'       => __( 'Search Templates', 'x4email-lite' ),
		'not_found'          => __( 'No templates found.', 'x4email-lite' ),
		'not_found_in_trash' => __( 'No templates found in Trash.', 'x4email-lite' ),
	);

	$args = array(
		'labels'       => $labels,
		'public'       => true,
		'show_in_menu' => false,
		'supports'     => array( 'title', 'editor', 'custom-fields' ),
		'has_archive'  => true,
		'rewrite'      => array( 'slug' => 'templates' ),
	);

	register_post_type( 'x4email_lt_tmplt', $args );

	// Flush rewrite rules when the custom post type is registered.
	flush_rewrite_rules();
}
add_action( 'init', 'x4email_register_template_post_type' );

/**
 * Load email templates from files and insert them into WordPress as custom posts.
 *
 * Scans the templates directory for PHP files and creates corresponding
 * WordPress posts for each template if they don't already exist.
 *
 * @since 1.0.0
 */
function x4email_lite_load_templates_as_posts() {
	$template_dir   = plugin_dir_path( __FILE__ ) . '../templates/';
	$template_files = glob( $template_dir . '*.php' );

	foreach ( $template_files as $template_file ) {
		$template_name    = basename( $template_file, '.php' );
		$template_content = file_get_contents( $template_file );

		// Check if the template already exists using WP_Query.
		$query = new WP_Query(
			array(
				'post_type'      => 'x4email_lt_tmplt',
				'title'          => $template_name,
				'posts_per_page' => 1,
			)
		);

		if ( ! $query->have_posts() ) {
			// If the template doesn't exist, insert it as a new post.
			wp_insert_post(
				array(
					'post_type'    => 'x4email_lt_tmplt',
					'post_title'   => $template_name,
					'post_content' => $template_content,
					'post_status'  => 'publish',
				)
			);
		}
	}
}

/**
 * Save template content to file when a template post is saved.
 *
 * Hook function that saves the content of email template posts
 * back to physical template files in the templates directory.
 *
 * @since 1.0.0
 *
 * @param int     $post_id The post ID.
 * @param WP_Post $post    The post object.
 * @param bool    $update  Whether this is an existing post being updated.
 */
function x4email_save_template_to_file( $post_id, $post, $update ) {
	if ( 'x4email_lt_tmplt' !== get_post_type( $post_id ) ) {
		return;
	}
	if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
		return;
	}
	if ( 'publish' !== get_post_status( $post_id ) ) {
		return;
	}

	$template_content = $post->post_content;
	$template_name    = sanitize_title_with_dashes( $post->post_title );

	// Save to uploads directory instead of plugin directory.
	$upload_dir   = wp_upload_dir();
	$template_dir = $upload_dir['basedir'] . '/x4email_lt_tmplt/';
	if ( ! file_exists( $template_dir ) ) {
		wp_mkdir_p( $template_dir );
	}

	$template_file = $template_dir . $template_name . '.php';
	$result        = file_put_contents( $template_file, $template_content );

	/*
	if ($result === false) {
		error_log( 'Failed to save template file: ' . $template_file );
	} else {
		error_log( 'Template saved successfully: ' . $template_file );
	} */
}
add_action( 'save_post', 'x4email_save_template_to_file', 10, 3 );
