<?php
/**
 * Plugin Name: X4EMAIL Lite
 * Description: A powerful WordPress email plugin with SMTP configuration, WooCommerce email templates, admin security features, email logs, and license validation system.
 * Version:     1.1.0
 * Author:      x4digital
 * Author URI:  https://x4digital.io/
 * License:     GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: x4email-lite
 * Domain Path: /languages
 */

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

// Block activation if Pro is active.
register_activation_hook( __FILE__, 'x4email_lite_block_activation_if_pro_active' );

/**
 * Block plugin activation if Pro version is active.
 *
 * Prevents the Lite version from being activated when the Pro version
 * is already active to avoid conflicts.
 *
 * @since 1.0.0
 */
function x4email_lite_block_activation_if_pro_active() {
	include_once ABSPATH . 'wp-admin/includes/plugin.php';
	$pro_plugin = 'x4mail-pro/x4email.php';
	if ( is_plugin_active( $pro_plugin ) ) {
		deactivate_plugins( plugin_basename( __FILE__ ) );
		wp_die(
			esc_html__( 'X4EMAIL Pro is already active. Please deactivate Pro before activating Lite.', 'x4email-lite' ),
			esc_html__( 'Plugin Activation Error', 'x4email-lite' ),
			array( 'back_link' => true )
		);
	}
}

// Prevent loading if Pro is active (in case both get activated somehow).
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$pro_plugin = 'x4mail-pro/x4email.php';
if ( function_exists( 'is_plugin_active' ) && is_plugin_active( $pro_plugin ) ) {
	return;
}

define( 'X4EMAIL_LITE_VER', '1.1.0' );
define( 'X4EMAIL_LITE_PLUGIN_FILE', __FILE__ );
define( 'X4EMAIL_PRO_URL', 'https://x4digital.io/' );
require_once plugin_dir_path( __FILE__ ) . 'includes/admin-menu.php';

register_activation_hook( __FILE__, 'x4email_lite_create_logs_table' );
register_activation_hook( __FILE__, 'x4email_lite_load_templates_as_posts' );

add_filter( 'woocommerce_locate_template', 'x4email_lite_custom_woocommerce_email_template', 10, 3 );

/**
 * Locate custom WooCommerce email templates.
 *
 * Overrides WooCommerce email template location to use custom templates
 * from the plugin or upload directory.
 *
 * @since 1.0.0
 *
 * @param string $template      Located template path.
 * @param string $template_name Template file name.
 * @param string $template_path Template path within theme.
 * @return string Modified template path.
 */
function x4email_lite_custom_woocommerce_email_template( $template, $template_name, $template_path ) {
	if ( strpos( $template_name, 'emails/' ) === 0 ) {
		$upload_dir      = wp_upload_dir();
		$custom_template = $upload_dir['basedir'] . '/x4email_lt_tmplt/' . basename( $template_name );
		if ( file_exists( $custom_template ) ) {
			return $custom_template;
		}

		$plugin_template = plugin_dir_path( __FILE__ ) . 'includes/templates/' . basename( $template_name );
		if ( file_exists( $plugin_template ) ) {
			return $plugin_template;
		}
	}
	return $template;
}

add_action(
	'admin_enqueue_scripts',
	function () {
		wp_enqueue_media();
	}
);

add_filter( 'woocommerce_email_classes', 'x4email_lite_override_woocommerce_email_templates' );

/**
 * Override WooCommerce email templates for all email classes.
 *
 * Adds filters to override core template locations for all WooCommerce
 * email classes to use custom templates.
 *
 * @since 1.0.0
 *
 * @param array $email_classes Array of WooCommerce email classes.
 * @return array Unmodified array of email classes.
 */
function x4email_lite_override_woocommerce_email_templates( $email_classes ) {
	foreach ( $email_classes as $email_class ) {
		add_filter(
			'woocommerce_locate_core_template',
			function ( $located, $template_name, $template_path ) {
				if ( strpos( $template_name, 'emails/' ) === 0 ) {
					$upload_dir      = wp_upload_dir();
					$custom_template = $upload_dir['basedir'] . '/x4email_lt_tmplt/' . basename( $template_name );
					if ( file_exists( $custom_template ) ) {
						return $custom_template;
					}

					$plugin_template = plugin_dir_path( __FILE__ ) . 'includes/templates/' . basename( $template_name );
					if ( file_exists( $plugin_template ) ) {
						return $plugin_template;
					}
				}
				return $located;
			},
			10,
			3
		);
	}
	return $email_classes;
}

require_once plugin_dir_path( __FILE__ ) . 'includes/pages/template-editor.php';

/**
 * Add template editor page to admin menu.
 *
 * Registers the template editor submenu page under the main plugin menu.
 *
 * @since 1.0.0
 */
function x4email_lite_add_template_editor_page() {
	add_submenu_page(
		'x4email-dashboard',
		__( 'Template Editor', 'x4email-lite' ),
		__( 'Template Editor', 'x4email-lite' ),
		'manage_options',
		'x4email-template-editor',
		'x4email_lite_template_editor_page'
	);
}
add_action( 'admin_menu', 'x4email_lite_add_template_editor_page' );

add_action( 'woocommerce_email_sent', 'x4email_lite_log_woocommerce_email', 10, 3 );
add_filter( 'wp_mail', 'x4email_lite_capture_email_details', 10, 1 );

/**
 * Capture email details before sending.
 *
 * Stores email details in a global variable for logging purposes
 * when emails are sent through wp_mail.
 *
 * @since 1.0.0
 *
 * @param array $args Email arguments (to, subject, message, headers, attachments).
 * @return array Unmodified email arguments.
 */
function x4email_lite_capture_email_details( $args ) {
	global $x4email_lite_current_mail;
	$x4email_lite_current_mail = $args;
	return $args;
}

/**
 * Log WooCommerce email sending attempts.
 *
 * Records email details, success/failure status, and error information
 * to the custom logs table for tracking and debugging purposes.
 *
 * @since 1.0.0
 *
 * @param bool   $success  Whether the email was sent successfully.
 * @param string $email_id WooCommerce email ID/type.
 * @param object $email    WooCommerce email object.
 */
function x4email_lite_log_woocommerce_email( $success, $email_id, $email ) {
	global $x4email_lite_current_mail;

	$to      = $x4email_lite_current_mail['to'] ?? $email->get_recipient();
	$subject = $x4email_lite_current_mail['subject'] ?? $email->get_subject();

	$message = $x4email_lite_current_mail['message'] ?? '';
	if ( empty( $message ) ) {
		if ( method_exists( $email, 'get_content_html' ) ) {
			$message = $email->get_content_html();
		} elseif ( method_exists( $email, 'get_content_plain' ) ) {
			$message = $email->get_content_plain();
		} elseif ( method_exists( $email, 'get_content' ) ) {
			$message = $email->get_content();
		}
	}

	$status = $success ? 'Successful' : 'Failed';
	global $phpmailer;
	$error_log = ! $success && isset( $phpmailer ) ? $phpmailer->ErrorInfo : 'No Errors';

	global $wpdb;
	$table_name = $wpdb->prefix . 'x4email_logs_lite';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table insert needed for plugin functionality.
	$wpdb->insert(
		$table_name,
		array(
			'mail_type'       => 'WooCommerce: ' . $email_id,
			'recipient_email' => $to,
			'subject'         => $subject,
			'message'         => $message,
			'status'          => $status,
			'error_log'       => $error_log,
			'sent_at'         => current_time( 'mysql' ),
		)
	);

	$x4email_lite_current_mail = null;
}

add_action(
	'admin_notices',
	function () {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}
		$screen = get_current_screen();
		if ( empty( $screen ) || strpos( $screen->id, 'x4email' ) === false ) {
			return;
		}

		include_once ABSPATH . 'wp-admin/includes/plugin.php';
		$wc_plugin       = 'woocommerce/woocommerce.php';
		$wc_plugin_path  = WP_PLUGIN_DIR . '/woocommerce/woocommerce.php';
		$is_wc_installed = file_exists( $wc_plugin_path );
		$is_wc_active    = is_plugin_active( $wc_plugin );

		if ( ! $is_wc_installed ) {
			$install_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' );
			echo '<div class="notice notice-error"><p>' .
			esc_html__( 'WooCommerce is required for X4EMAIL Lite to work. ', 'x4email-lite' ) .
			'<a href="' . esc_url( $install_url ) . '" class="button button-primary">' . esc_html__( 'Install WooCommerce', 'x4email-lite' ) . '</a>' .
			'</p></div>';
		} elseif ( ! $is_wc_active ) {
			$activate_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=' . urlencode( $wc_plugin ) ), 'activate-plugin_' . $wc_plugin );
			echo '<div class="notice notice-warning"><p>' .
			esc_html__( 'WooCommerce needs to be active for X4EMAIL Lite to work. ', 'x4email-lite' ) .
			'<a href="' . esc_url( $activate_url ) . '" class="button button-primary">' . esc_html__( 'Activate WooCommerce', 'x4email-lite' ) . '</a>' .
			'</p></div>';
		}
	}
);
