<?php
namespace BricksUltimate\WooCommerce;

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

use BricksUltimate\Plugin;

class WooEmails {
	function __construct() {
		if( 'yes' !== get_option( 'woocommerce_custom_orders_table_enabled' ) )
			return;

		add_filter( 'bricks/setup/control_options', [$this, 'setup_email_templates'] );
		add_filter( 'woocommerce_locate_template', [ $this, 'bu_wc_email_template' ], 1000, 3 );
		add_filter( 'woocommerce_email_content_low_stock', [ $this, 'bu_wc_low_stock'], 10, 2 );
		add_filter( 'woocommerce_email_content_no_stock', [ $this, 'bu_wc_no_stock'], 10, 2 );
		add_filter( 'woocommerce_email_headers', [ $this, 'bu_wc_email_headers'], 10, 4 );

		add_action( 'generate_email_template_css', [ $this, 'bu_prepare_wc_email_template'], 10, 2);
	}

	/**
	 * Loading the inline css for the WooCommerce email templates
	 * 
	 * @param string $type Template type
	 * @param string $template_content HTML content from the Bricks editor
	 */
	public function bu_prepare_wc_email_template( $type, $template_content ) {
		add_filter('woocommerce_email_styles', function($css){ return ''; });
		
		$inline_css = $this->bu_get_builder_inline_css( $type );

		echo "<style>{$inline_css}.bu-image-item{padding-bottom: 0!important;}</style>";
		echo $template_content;
	}

	public function bu_get_builder_inline_css( $type ) {
		$template_id = \Bricks\Woocommerce::get_template_data_by_type( $type, false );
		$elements = \Bricks\Database::get_data( $template_id, $type );

		$inline_css = '';
		$inline_css .= \Bricks\Assets::generate_inline_css( $template_id );

		$inline_css .= file_get_contents( BRICKS_PATH_ASSETS . 'css/frontend-light.min.css' );

		if ( is_rtl() ) {
			$inline_css .= file_get_contents( BRICKS_PATH_ASSETS . 'css/frontend-rtl.min.css' );
		}

		$inline_css .= file_get_contents( BRICKS_PATH_ASSETS . 'css/libs/font-awesome-6.min.css' );
		$inline_css .= file_get_contents( BRICKS_PATH_ASSETS . 'css/libs/font-awesome-6-brands.min.css' );
		$inline_css .= file_get_contents( BRICKS_PATH_ASSETS . 'css/libs/ionicons.min.css' );
		$inline_css .= file_get_contents( BRICKS_PATH_ASSETS . 'css/libs/themify-icons.min.css' );

		$inline_css = str_replace('../../fonts', BRICKS_URL_ASSETS . '/fonts', $inline_css);

		\Bricks\Assets::generate_global_classes();

		$inline_css .= \Bricks\Assets::$inline_css['global_classes'];
		$inline_css .= \Bricks\Assets::$inline_css_dynamic_data;

		\Bricks\Assets::generate_css_from_elements( $elements, "template_$template_id" );
		$inline_css .= \Bricks\Assets::$inline_css[ "template_$template_id" ] ?? '';

		return $inline_css;
	}

	public function bu_wc_email_headers( $header, $email_type, $product, $object ) {
		if( ! in_array( $email_type, ['low_stock', 'no_stock'] ) )
			return $header;

		$template_id = \Bricks\Woocommerce::get_template_data_by_type( "wce_" . $email_type, false );
		if( $template_id !== false ) {
			$header = 'Content-Type: text/html' . "\r\n";
			$header .= 'Reply-to: ' . get_option( 'woocommerce_email_from_name' ) . ' <' . get_option( 'woocommerce_stock_email_recipient' ) . ">\r\n";
		}

		return $header;
	}

	public function bu_wc_low_stock( $message, $low_stock_product ) {
		$type = 'wce_low_stock';
		$template_id = \Bricks\Woocommerce::get_template_data_by_type( $type, false );
		if( $template_id !== false ) {
			$message = $this->bu_prepare_low_no_stock_email_template( $type );
		}

		return $message;
	}

	public function bu_wc_no_stock( $message, $no_stock_product ) {
		$type = 'wce_no_stock';
		$template_id = \Bricks\Woocommerce::get_template_data_by_type( $type, false );
		if( $template_id !== false ) {
			$message = $this->bu_prepare_low_no_stock_email_template( $type );
		}

		return $message;
	}

	public function bu_prepare_low_no_stock_email_template( $type ) {
		global $product;
		$product = $no_stock_product;
		\setup_postdata( $product );
		$inline_css = $this->bu_get_builder_inline_css( $type );
		$html = $this->get_email_template_header();
		$html .= "<style>{$inline_css}.bu-image-item{padding-bottom: 0!important;}</style>";
		$html .= \Bricks\Woocommerce::get_template_data_by_type( $type );
		$html .= $this->get_email_template_footer();
		\wp_reset_postdata();

		return $html;
	}

	public function get_email_template_header() {
		ob_start();
		?>
		<!DOCTYPE html>
		<html <?php language_attributes(); ?>>
			<head>
				<meta http-equiv="Content-Type" content="text/html; charset=<?php bloginfo( 'charset' ); ?>" />
				<meta content="width=device-width, initial-scale=1.0" name="viewport">
				<title><?php echo get_bloginfo( 'name', 'display' ); ?></title>
			</head>
			<body <?php echo is_rtl() ? 'rightmargin' : 'leftmargin'; ?>="0" marginwidth="0" topmargin="0" marginheight="0" offset="0">
		<?php

		return ob_get_clean();
	}

	public function get_email_template_footer() {
		return '</body></html>';
	}
	public function bu_wc_email_template( $template, $template_name, $template_path ) {
		$root = Plugin::instance()->get_root_path();
		$new_template = false;

		//* email templates
		$adm_new_ord_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_admin_new_order', false );
		if( $adm_new_ord_tpl !== false && $template_name === 'emails/admin-new-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$cancelled_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_admin_cancel_order', false );
		if( $cancelled_tpl !== false && $template_name === 'emails/admin-cancelled-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$failed_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_admin_failed_order', false );
		if( $failed_tpl !== false && $template_name === 'emails/admin-failed-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$invoice_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_customer_invoice', false );
		if( $invoice_tpl !== false && $template_name === 'emails/customer-invoice.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$hold_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_hold_order', false );
		if( $hold_tpl !== false && $template_name === 'emails/customer-on-hold-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$completed_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_completed_order', false );
		if( $completed_tpl !== false && $template_name === 'emails/customer-completed-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$processing_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_processing_order', false );
		if( $processing_tpl !== false && $template_name === 'emails/customer-processing-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}

		$refunded_tpl = \Bricks\Woocommerce::get_template_data_by_type( 'wce_refund_order', false );
		if( $refunded_tpl !== false && $template_name === 'emails/customer-refunded-order.php' /*&& ! is_admin()*/ ) {
			$new_template = $root . 'templates/' . $template_name;
		}
		//* email templates

		if( $new_template !== false && file_exists( $new_template ) )
			return $new_template;

		return $template;
	}

	public function setup_email_templates( $control_options ) {
		$template_types = $control_options['templateTypes'];
		$template_types['wce_low_stock'] 			= esc_html__('WooCommerce - Email - Low stock', 'bricksultimate');
		$template_types['wce_no_stock'] 			= esc_html__('WooCommerce - Email - No stock', 'bricksultimate');
		$template_types['wce_admin_new_order'] 		= esc_html__('WooCommerce - Email - Admin - New Order', 'bricksultimate');
		$template_types['wce_admin_cancel_order'] 	= esc_html__('WooCommerce - Email - Admin - Cancelled Order', 'bricksultimate');
		$template_types['wce_admin_failed_order'] 	= esc_html__('WooCommerce - Email - Admin - Failed Order', 'bricksultimate');
		$template_types['wce_customer_invoice'] 	= esc_html__('WooCommerce - Email - Customer Invoice', 'bricksultimate');
		$template_types['wce_completed_order'] 		= esc_html__('WooCommerce - Email - Completed Order', 'bricksultimate');
		$template_types['wce_processing_order'] 	= esc_html__('WooCommerce - Email - Processing Order', 'bricksultimate');
		$template_types['wce_hold_order'] 			= esc_html__('WooCommerce - Email - On Hold Order', 'bricksultimate');
		$template_types['wce_refund_order'] 		= esc_html__('WooCommerce - Email - Refunded Order', 'bricksultimate');

		$control_options['templateTypes'] 	= $template_types;

		return $control_options;
	}
}