<?php
namespace NCPC\classes;

/**
 * Contains all methods and hooks callbacks related to the design
 *
 * @author Vertim Coders
 */
class NCPC_Design
{
	/**
	 * Set all ncpc configuration initialization hooks
	 */
	public function init_hooks()
	{
		//admin data
		add_action('woocommerce_after_order_itemmeta', [$this, 'get_order_custom_admin_data'], 10, 3);
		add_action('woocommerce_review_order_after_cart_contents', [$this, 'display_recaps_config_on_checkout_page']);
		add_action('woocommerce_checkout_create_order_line_item', [$this, 'capture_product_metadata_to_order'], 10, 4);

		// Emails.
		add_action('woocommerce_order_item_meta_start', [$this, 'set_email_order_item_meta'], 10, 3);
		add_filter('woocommerce_email_attachments', [$this, 'add_order_design_to_mail'], 10, 3);
		add_action('woocommerce_order_item_meta_end', [$this, 'mail_template'], 11, 4);
	}

	/**
	 * Retourne la liste de balises autorisées pour nos récapitulatifs,
	 * en y ajoutant <style> et l’attribut style.
	 */
	private function get_allowed_recap_tags()
	{
		// commence avec la liste standard « post »
		$allowed = wp_kses_allowed_html('post');

		// autorise la balise <style> (sans aucun attribut)
		$allowed['style'] = [];

		// autorise l’attribut style sur les balises courantes
		$tags = ['div', 'span', 'h4', 'button', 'p', 'img'];
		foreach ($tags as $tag) {
			if (isset($allowed[$tag])) {
				$allowed[$tag]['style'] = true;
			}
		}

		return $allowed;
	}

	/**
	 * Render recap data HTML with improved styling
	 *
	 * @param array $order_data
	 * @return string
	 */
	private function render_recap_data($order_data)
	{
		if (empty($order_data)) {
			return '';
		}

		ob_start();
		?>
		<!-- Conteneur principal avec font-family, taille, spacing, etc. -->
		<div class="ncpc-recap-container" style="
			padding: 20px;	  
			font-size: 10px;
			line-height: 1.4;
			">
			<!-- Flex wrap pour disposition flexible -->
			<div class="ncpc-recap-grid" style="
		   display: flex;
		   flex-wrap: wrap;
		   gap: 15px;
		   justify-content: space-between;
		   align-items: flex-start;
		 ">
				<?php
				// Fonction pour traiter chaque élément individuellement
				$process_item = function ($item, $label = null) {
					if (is_array($item) && isset($item['label'])) {
						// Élément avec structure label/value
						?>
						<div class="ncpc-recap-item" style="
					   display: flex;
					   align-items: flex-start;
					   flex-direction: column;
					   margin-bottom: 15px;
					   flex: 1 1 45%;
					   min-width: 250px;
					 ">
							<!-- Label et valeur sur la même ligne -->
							<div class="ncpc-recap-row" style="
						   display: flex;
						   align-items: flex-start;
						   width: 100%;
						   gap: 8px;
						 ">
								<span class="ncpc-recap-label" style="
								font-weight: 600;
								color: #333;
								min-width: 80px;
								flex-shrink: 0;
							  ">
									<?= esc_html($item['label']); ?>:
								</span>

								<span class="ncpc-recap-value" style="
								color: #666;
								flex-grow: 1;
							  ">
									<?php
									if (is_array($item['value'])):
										// Vérifier si c'est un tableau de structures label/value
										$is_structured = false;
										foreach ($item['value'] as $sub_item) {
											if (is_array($sub_item) && (isset($sub_item['label']) || isset($sub_item['value']))) {
												$is_structured = true;
												break;
											}
										}

										if ($is_structured):
											// Affichage pour les structures label/value
											?>
											<div class="ncpc-subvalues" style="margin-left: 10px;">
												<?php foreach ($item['value'] as $sub_item): ?>
													<div class="ncpc-subvalue-item" style="
													display: flex;
													margin-bottom: 3px;
													align-items: flex-start;
													gap: 8px;
												  ">
														<?php if (isset($sub_item['label'])): ?>
															<span class="ncpc-sublabel" style="
															font-weight: 500;
															color: #444;
															min-width: 80px;
															flex-shrink: 0;
														  ">
																<?= esc_html($sub_item['label']); ?>:
															</span>
														<?php endif; ?>

														<?php if (isset($sub_item['value'])): ?>
															<span class="ncpc-subvalue" style="
															color: #666;
															flex-grow: 1;
														  ">
																<?= esc_html(is_array($sub_item['value']) ? implode(', ', $sub_item['value']) : $sub_item['value']); ?>
															</span>
														<?php endif; ?>
													</div>
												<?php endforeach; ?>
											</div>
											<?php
										else:
											// Tableau simple
											echo esc_html(implode(', ', $item['value']));
										endif;
									else:
										// Valeur simple
										echo esc_html($item['value']);
									endif;
									?>
								</span>
							</div>
						</div>
						<?php
					}
				};

				// Parcourir les données
				foreach ($order_data as $key => $recap):
					// Cas 1: Structure avec label/value
					if (is_array($recap) && isset($recap['label'])) {
						$process_item($recap);
					}
					// Cas 2: Tableau d'éléments (comme additionalOptions)
					elseif (is_array($recap) && !isset($recap['label'])) {
						// Traiter chaque élément du tableau individuellement
						foreach ($recap as $item) {
							$process_item($item);
						}
					}
					// Cas 3: Valeur simple (comme customPrice) - on l'ignore car pas de structure label/value
					// Ne rien faire pour les valeurs simples
				endforeach;
				?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render preview and download buttons
	 *
	 * @param array $order_data
	 * @param int $item_id
	 * @param bool $is_admin
	 * @return string
	 */
	private function render_preview_and_downloads($order_data, $item_id, $is_admin = false)
	{
		if (empty($order_data)) {
			return '';
		}

		ob_start();
		$modal_id = uniqid() . $item_id;

		if (isset($order_data['ncpc_preview_img'])) {
			if ($is_admin) {
				?>
				<div style="margin:10px 0">
					<button class="button alt ncpc_admin_download_image"
						data-img-url="<?php echo esc_attr($order_data['ncpc_preview_img']); ?>"><?php echo __('Download', "neon-channel-product-customizer-free"); ?></button>
					<span><a class="o-modal-trigger button" data-toggle="o-modal"
							data-target="#<?php echo esc_attr($modal_id); ?>"><?php echo __('Preview', "neon-channel-product-customizer-free"); ?></a></span>
					<div class="omodal fade o-modal wpc_part" id="<?php echo esc_attr($modal_id); ?>" tabindex="-1" role="dialog"
						aria-labelledby="myModalLabel" aria-hidden="true">
						<div class="omodal-dialog">
							<div class="omodal-content">
								<div class="omodal-header">
									<button type="button" class="close" data-dismiss="omodal" aria-hidden="true">&times;</button>
									<h4 class="omodal-title" id="myModalLabel<?php echo esc_attr($modal_id); ?>">Preview</h4>
								</div>
								<div class="omodal-body">
									<img width="100%" height="100%" src="<?php echo esc_url($order_data['ncpc_preview_img']); ?>">
								</div>
							</div>
						</div>
					</div>
				</div>
				<?php
			} else {
				?>
				<div>
					<h4 class="omodal-title" id="myModalLabel<?php echo esc_attr($modal_id); ?>">Preview</h4>
					<div class="omodal-body">
						<img src="<?php echo esc_url($order_data['ncpc_preview_img']); ?>">
					</div>
				</div>
				<?php
			}
		}

		if (isset($order_data['ncpc_svg_data'])) {
			if ($is_admin) {
				?>
				<div style="margin:10px 0">
					<button class="button alt ncpc_admin_download_svg"
						href='<?php echo esc_attr($order_data['ncpc_svg_data']); ?>'><?php echo __('Download SVG', "neon-channel-product-customizer-free"); ?></button>
				</div>
				<?php
			} else {
				?>
				<div style="margin:10px 0">
					<a class="button alt ncpc_admin_download_image" href="<?php echo esc_attr($order_data['ncpc_preview_img']); ?>"
						download><?php echo __('Download Image', "neon-channel-product-customizer-free"); ?></a>
					<a class="button alt ncpc_admin_download_svg" href='<?php echo esc_attr($order_data['ncpc_svg_data']); ?>'
						download><?php echo __('Download SVG', "neon-channel-product-customizer-free"); ?></a>
				</div>
				<?php
			}
		}

		return ob_get_clean();
	}

	/**
	 * Add in mail the recap data.
	 *
	 * @param int   $item_id The item id.
	 * @param array $item The item data.
	 * @param mixed $order The order data.
	 * @return mixed
	 */
	public function set_email_order_item_meta($item_id, $item, $order)
	{
		if (is_order_received_page()) {
			return;
		}

		$order_data = wc_get_order_item_meta($item_id, 'ncpc_recaps');
		if (empty($order_data)) {
			return;
		}

		$html = $this->render_recap_data($order_data);
		$html .= $this->render_preview_and_downloads($order_data, $item_id, false);

		return $html;
	}

	/**
	 * Add order design to mail.
	 *
	 * @param array $attachments
	 * @param string $status
	 * @param  object $order
	 * @return array
	 */
	public function add_order_design_to_mail($attachments, $status, $order)
	{
		$allowed_statuses = array('new_order', 'customer_invoice', 'customer_processing_order', 'customer_completed_order');

		if (!isset($status) || !in_array($status, $allowed_statuses)) {
			return $attachments;
		}

		$items = $order->get_items();
		foreach ($items as $item) {
			$ncpc_recaps = $item->get_meta('ncpc_recaps');
			if (!empty($ncpc_recaps)) {
				if (isset($ncpc_recaps['ncpc_preview_img'])) {
					$attachments[] = $ncpc_recaps['ncpc_preview_img'];
				}
				if (isset($ncpc_recaps['ncpc_svg_data'])) {
					$attachments[] = $ncpc_recaps['ncpc_svg_data'];
				}
			}
		}

		return $attachments;
	}

	/**
	 * Display custom admin data for orders
	 */
	public function get_order_custom_admin_data($item_id, $item, $_product)
	{
		$order_data = wc_get_order_item_meta($item_id, 'ncpc_recaps');
		$order_id = $item->get_order_id();

		if (!$order_id || empty($order_data)) {
			return;
		}

		// Render recap data and preview
		echo $this->render_recap_data($order_data);
		echo $this->render_preview_and_downloads($order_data, $item_id, true);

		// Render manufacturer email button if configured
		$this->render_manufacturer_email_button($_product, $order_data, $order_id);
	}

	/**
	 * Render manufacturer email button
	 */
	private function render_manufacturer_email_button($_product, $order_data, $order_id)
	{
		$product_id = $_product->get_id();
		$email_config = $this->get_manufacturer_email_config($product_id);

		if (!$email_config || !$email_config['sendDesignByEmail'] || empty($email_config['receiverEmail'])) {
			return;
		}

		?>
		<div>
			<button class="button ncpc-send-email" data-product-id="<?php echo esc_attr($product_id); ?>"
				data-order='<?php echo wp_json_encode(["recaps" => $order_data, "order_id" => $order_id]); ?>'>
				<?php echo __("Send Manufacturer mail", "neon-channel-product-customizer-free"); ?>
			</button>
		</div>
		<?php
	}

	/**
	 * Get manufacturer email configuration
	 */
	private function get_manufacturer_email_config($product_id)
	{
		$meta = get_post_meta($product_id, 'product-ncpc-metas', true);

		if (empty($meta) || !isset($meta[$product_id]['config-id'])) {
			return false;
		}

		$config_id = $meta[$product_id]['config-id'];
		if ($config_id == 0) {
			return false;
		}

		$config = get_post_meta($config_id, "ncpc-configs-meta", true);
		if (empty($config)) {
			return false;
		}

		return $config['data']['settings']['generals']['output']['manufacturerEmail'] ?? false;
	}

	/**
	 * Display recaps on checkout page
	 */
	public function display_recaps_config_on_checkout_page()
	{
		if ((defined('DOING_AJAX') && DOING_AJAX) || !is_checkout()) {
			return;
		}

		foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
			$product = $cart_item['data'];
			$order_data = $cart_item['ncpc_recaps'] ?? [];

			if (!$product || empty($order_data)) {
				continue;
			}

			$product_id = $product->get_id();
			if (!$this->should_display_recaps_on_checkout($product_id)) {
				continue;
			}

			echo $this->render_recap_data($order_data);
		}
	}

	/**
	 * Check if recaps should be displayed on checkout
	 */
	private function should_display_recaps_on_checkout($product_id)
	{
		$product_meta_data = get_post_meta($product_id, 'product-ncpc-metas', true);

		if (!isset($product_meta_data[$product_id]['config-id'])) {
			return false;
		}

		$config_id = $product_meta_data[$product_id]['config-id'];
		if (!get_post($config_id)) {
			return false;
		}

		$config = get_post_meta($config_id, "ncpc-configs-meta", true);

		return isset($config["data"]["settings"]["generals"]["product"]["displayRecapsOnCheckout"])
			&& $config["data"]["settings"]["generals"]["product"]["displayRecapsOnCheckout"];
	}

	/**
	 * Capture product metadata to order
	 */
	public function capture_product_metadata_to_order($item, $cart_item_key, $values, $order)
	{
		$meta_key = 'ncpc_recaps';

		if (!isset($values[$meta_key])) {
			return;
		}

		$meta_data = $values[$meta_key];

		if (isset($values['ncpc_preview_img'])) {
			$meta_data['ncpc_preview_img'] = $values['ncpc_preview_img'];
		}

		if (isset($values['ncpc_svg_data'])) {
			$meta_data['ncpc_svg_data'] = $values['ncpc_svg_data'];
		}

		$item->update_meta_data($meta_key, $meta_data);
	}

	/**
	 * Mail template rendering
	 */
	public function mail_template($item_id, $item, $_product)
	{
		$order_data = wc_get_order_item_meta($item_id, 'ncpc_recaps');

		if (empty($order_data)) {
			return;
		}

		$html = $this->render_recap_data($order_data);
		$html .= $this->render_preview_and_downloads($order_data, $item_id, false);

		echo $html;
	}

	/**
	 * Prepare email data from order and recaps
	 */
	private function prepare_email_data($order, $recaps)
	{
		$email_data = [
			'shipping_address.name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
			'shipping_address.phone' => $order->get_billing_phone(),
			'shipping_address.address1' => $order->get_shipping_address_1(),
			'shipping_address.address2' => $order->get_shipping_address_2(),
			'shipping_address.city' => $order->get_shipping_city(),
			'shipping_address.country' => $order->get_shipping_country(),
			'shipping_address.postcode' => $order->get_shipping_postcode(),
			'email' => $order->get_billing_email(),
			'shipping_line' => $order->get_shipping_method(),
			'order_id' => $order->get_id(),
			'order_date' => $order->get_date_created()->format('Y-m-d H:i:s'),
		];

		// Process ncpc_text if it's an array
		if (isset($recaps['ncpc_text']['value']) && is_array($recaps['ncpc_text']['value'])) {
			$recaps['ncpc_text']['value'] = implode(' / ', $recaps['ncpc_text']['value']);
		}

		// Merge with recaps data
		foreach ($recaps as $key => $value) {
			if ($key !== 'ncpc_additional_option') {
				$email_data[$key] = is_array($value) ? $value['value'] : $value;
			}
		}

		return $email_data;
	}

	/**
	 * Process email template with data
	 */
	private function process_email_template($template, $data, $additional_options = [])
	{
		// Replace simple placeholders
		foreach ($data as $key => $value) {
			$placeholder = '{{' . $key . '}}';
			$template = str_replace($placeholder, $value, $template);
		}

		// Process additional options section
		if (!empty($additional_options)) {
			$pattern = '/{{#additonal_options}}(.+?){{\/additonal_options}}/s';
			$additional_content = '';

			foreach ($additional_options as $option) {
				$additional_content .= '<b>' . esc_html($option["label"]) . '</b>: ' . esc_html($option["value"]) . '<br>';
			}

			$template = preg_replace($pattern, $additional_content, $template);
		}

		// Remove any remaining placeholders
		$template = preg_replace('/{{.*?}}/', '', $template);
		$template = str_replace('\\n', '', $template);

		return $template;
	}

	/**
	 * Create email attachments
	 */
	private function create_email_attachments($svg_data)
	{
		if (empty($svg_data)) {
			return [];
		}

		$file_content = file_get_contents($svg_data);
		if ($file_content === false) {
			return [];
		}

		return [
			'ncpc-custom-text.svg' => $file_content
		];
	}

	/**
	 * Send manufacturer email - Optimized version
	 */
	public function send_manufactrer_email()
	{
		// Security checks
		if (!wp_verify_nonce($_POST['nonce'] ?? '', 'ncpc_manufacturer_email')) {
			wp_send_json_error(['message' => __('Security check failed', 'neon-channel-product-customizer-free')]);
			return;
		}

		try {
			$product_id = intval($_POST['product_id']);
			$order_id = intval($_POST['order_id']);
			$recaps = $_POST['recaps'] ?? [];

			// Get order and validate
			$order = wc_get_order($order_id);
			if (!$order) {
				throw new Exception(__('Order not found', 'neon-channel-product-customizer-free'));
			}

			// Get email configuration
			$email_config = $this->get_manufacturer_email_config($product_id);
			if (!$email_config || !$email_config['sendDesignByEmail']) {
				throw new Exception(__('Email configuration not found', 'neon-channel-product-customizer-free'));
			}

			// Prepare email data
			$email_data = $this->prepare_email_data($order, $recaps);

			// Process email template
			$email_message = $this->process_email_template(
				$email_config['emailTemplate'],
				$email_data,
				$recaps['ncpc_additional_option'] ?? []
			);

			// Prepare email
			$to_emails = implode(',', $email_config['receiverEmail']);
			$subject = $email_config['subject'];
			$headers = [
				'From: ' . get_option('admin_email'),
				'Content-Type: text/html; charset=UTF-8'
			];

			// Create attachments
			$attachments = $this->create_email_attachments($recaps['ncpc_svg_data'] ?? '');

			// Send email
			$sent = wp_mail($to_emails, $subject, $email_message, $headers, $attachments);

			if ($sent) {
				wp_send_json_success(['message' => __('Email sent successfully', 'neon-channel-product-customizer-free')]);
			} else {
				throw new Exception(__('Email sending failed', 'neon-channel-product-customizer-free'));
			}

		} catch (Exception $e) {
			wp_send_json_error(['message' => $e->getMessage()]);
		}
	}
}
