<?php

namespace Ilabs\Inpost_International\Emails;

use Ilabs\Inpost_International\Helpers\Helper;
use WooCommerce;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly.

class TrackingInfoEmail {


	/**
	 * Sends tracking information email to the customer.
	 *
	 * This function checks if sending email on package creation is enabled in the settings.
	 * If enabled, it prepares and sends an email with tracking information to the customer.
	 *
	 * @param int    $order_id        The ID of the WooCommerce order.
	 * @param string $tracking_number The tracking number for the shipment.
	 *
	 * @return void
	 *
	 * @uses Helper::get_tracking_url()
	 * @uses get_tracking_info_email_html()
	 *
	 * @global WooCommerce $woocommerce
	 */
	public function send_tracking_info_email( $order_id, $tracking_number ) {

		$sending_options                 = get_option( 'inpost_international_settings_sending' );
		$is_send_email_on_package_create = $sending_options['send_email_after_package_created'];

		if ( $is_send_email_on_package_create ) {

			$order = wc_get_order( $order_id );

			if ( ! $order || is_wp_error( $order ) ) {
				return;
			}

			$helper       = new Helper();
			$tracking_url = $helper->get_tracking_url();
			$order_email  = $order->get_billing_email();
			// load the mailer class.
			$mailer    = WC()->mailer();
			$recipient = $order_email;
			$subject   = esc_html__( 'Your order has been given a tracking number', 'inpost-international' );
			$content   = $this->get_tracking_info_email_html( $tracking_url, $tracking_number, $order, $mailer, $subject );
			$headers   = "Content-Type: text/html\r\n";
			$mailer->send( $recipient, $subject, $content, $headers );
		}
	}

	/**
	 * Generates HTML content for tracking information email.
	 *
	 * This function retrieves an HTML template for the tracking information email
	 * and populates it with the provided data.
	 *
	 * @param string                                   $tracking_link   The URL for tracking the shipment.
	 * @param string                                   $tracking_number The tracking number for the shipment.
	 * @param WC_Order|bool|\WC_Order|\WC_Order_Refund $order           The WooCommerce order object.
	 * @param \WC_Emails                               $mailer          The WooCommerce email object.
	 * @param string|false                             $heading         Optional. The email heading. Default false.
	 *
	 * @return string The generated HTML content for the tracking information email.
	 */
	private function get_tracking_info_email_html( $tracking_link, $tracking_number, $order, $mailer, $heading = false ) {

		return wc_get_template_html(
			'emails/send-tracking-to-buyer.php',
			array(
				'tracking_link'   => $tracking_link,
				'tracking_number' => $tracking_number,
				'order'           => $order,
				'email_heading'   => $heading,
				'sent_to_admin'   => false,
				'plain_text'      => false,
				'email'           => $mailer,
			)
		);
	}
}
