<?php

namespace WarrantyCart\Notifications\Emails;

use Dompdf\Dompdf;
use WC_Email;
use WC_Order;

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

/**
 * Warranty Order Completion Email
 *
 * Email sent to customer when warranty order is completed.
 */
class OrderCompletion extends WC_Email {

	/**
	 * Order object
	 *
	 * @var WC_Order|null
	 */
	public ?WC_Order $order = null;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->id                     = 'warranty_order_completed';
		$this->title                  = __( 'Warranty Order Completed', 'warranty-cart' );
		$this->description            = __( 'Email sent to customer when a warranty order is completed.', 'warranty-cart' );
		$this->template_base          = WARRANTY_CART_PATH . 'templates/';
		$this->template_html          = 'emails/warranty-order-completed.php';
		$this->template_plain         = 'emails/plain/warranty-order-completed.php';
		$this->template_block_content = 'emails/block/warranty-order-completed.php';
		$this->customer_email         = true;

		parent::__construct();

		$this->template_base = WARRANTY_CART_PATH . 'templates/';
		$this->placeholders  = array_merge(
			$this->placeholders,
			array(
				'{order_date}'    => '',
				'{order_number}'  => '',
				'{customer_name}' => '',
			)
		);
	}

	/**
	 * Get email subject
	 *
	 * @return string
	 */
	public function get_default_subject() {
		return __( 'Your warranty purchase has been confirmed - Order #{order_number}', 'warranty-cart' );
	}

	/**
	 * Get email heading
	 *
	 * @return string
	 */
	public function get_default_heading() {
		return __( 'Warranty Purchase Confirmed', 'warranty-cart' );
	}

	/**
	 * Trigger email
	 *
	 * @param int $order_id Order ID.
	 */
	public function trigger( $order_id ) {
		$this->setup_locale();

		if ( $order_id ) {
			$order = wc_get_order( $order_id );

			if ( $order instanceof \WC_Order ) {
				$this->order                           = $order;
				$this->recipient                       = $this->order->get_billing_email();
				$this->placeholders['{order_date}']    = wc_format_datetime( $this->order->get_date_created() );
				$this->placeholders['{order_number}']  = $this->order->get_order_number();
				$this->placeholders['{customer_name}'] = $this->order->get_billing_first_name();
			}
		}

		if ( $this->is_enabled() && $this->get_recipient() ) {
			$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
		}

		$this->restore_locale();
	}

	/**
	 * Get content html
	 *
	 * @return string
	 */
	public function get_content_html() {
		return wc_get_template_html(
			$this->template_html,
			array(
				'order'              => $this->order,
				'email_heading'      => $this->get_heading(),
				'additional_content' => $this->get_additional_content(),
				'sent_to_admin'      => false,
				'plain_text'         => false,
				'email'              => $this,
			),
			'',
			$this->template_base
		);
	}

	/**
	 * Get content plain
	 *
	 * @return string
	 */
	public function get_content_plain() {
		return wc_get_template_html(
			$this->template_plain,
			array(
				'order'              => $this->order,
				'email_heading'      => $this->get_heading(),
				'additional_content' => $this->get_additional_content(),
				'sent_to_admin'      => false,
				'plain_text'         => true,
				'email'              => $this,
			),
			'',
			$this->template_base
		);
	}

	/**
	 * Get block editor email template content.
	 *
	 * @return string
	 */
	public function get_block_editor_email_template_content() {
		return wc_get_template_html(
			$this->template_block_content,
			array(
				'order'              => $this->order,
				'email_heading'      => $this->get_heading(),
				'additional_content' => $this->get_additional_content(),
				'sent_to_admin'      => false,
				'plain_text'         => false,
				'email'              => $this,
			),
			'',
			$this->template_base
		);
	}

	/**
	 * Get attachments
	 *
	 * Returns PDF warranty certificate attachment for the email.
	 *
	 * @return array Array of attachment file paths.
	 */
	public function get_attachments() {
		$attachments = array();

		/*
		 * The "PDF certificates" setting, finally consulted.
		 *
		 * Everything needed to honour it already existed -- DomPDF is a
		 * dependency, the certificate template is in templates/pdf/, and
		 * generate_warranty_pdf() below renders it. The only missing piece was
		 * anybody asking whether the setting was on, so switching it off
		 * changed nothing and every order still shipped a certificate.
		 */
		if ( ! (bool) get_option( 'warranty_enable_pdf_certificates', true ) ) {
			return $attachments;
		}

		if ( $this->order ) {
			// Generate and attach warranty PDF
			$warranty_pdf = $this->generate_warranty_pdf();
			if ( $warranty_pdf ) {
				$attachments[] = $warranty_pdf;
			}
		}

		return $attachments;
	}

	/**
	 * Generate warranty PDF
	 *
	 * Creates a PDF warranty certificate for the order.
	 *
	 * @return string|null PDF file path or null on failure.
	 * @throws \Exception When order is not set or PDF generation fails.
	 */
	public function generate_warranty_pdf() {
		try {
			// Check if order is set
			if ( ! $this->order instanceof WC_Order ) {
				throw new \Exception( 'Order not set for PDF generation' );
			}

			// Load DomPDF if not already loaded
			if ( ! class_exists( Dompdf::class ) ) {
				require_once WARRANTY_CART_PATH . 'vendor/dompdf/dompdf/src/Dompdf.php';
			}

			$dompdf = new \Dompdf\Dompdf();
			$dompdf->set_option( 'isHtml5ParserEnabled', true );
			$dompdf->set_option( 'isRemoteEnabled', false );

			// Get PDF template
			ob_start();
			wc_get_template(
				'pdf/warranty-certificate.php',
				array( 'order' => $this->order ),
				'warranty-cart',
				WARRANTY_CART_PATH . 'templates/'
			);
			$html = ob_get_clean();

			$dompdf->loadHtml( $html );
			$dompdf->setPaper( 'A4', 'portrait' );
			$dompdf->render();

			// Create uploads directory if it doesn't exist
			$upload_dir   = wp_upload_dir();
			$warranty_dir = $upload_dir['basedir'] . '/warranties';

			if ( ! file_exists( $warranty_dir ) ) {
				wp_mkdir_p( $warranty_dir );
			}

			$filename  = 'warranty-' . $this->order->get_id() . '.pdf';
			$file_path = $warranty_dir . '/' . $filename;

			warranty_cart()->write_file( $file_path, $dompdf->output() );

			return $file_path;
		} catch ( \Throwable $e ) {
			warranty_cart()->log( 'Warranty PDF generation failed: ' . $e->getMessage(), 'error' );

			return null;
		}
	}
}
