<?php
/**
 * ETYKIETOWNIK email — sends label PDF + packing list after generation.
 *
 * @package ParcelSelector
 * @since   3.4.0
 */

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

// phpcs:disable WordPress.WP.I18n.MissingTranslatorsComment -- Translators comments are placed before sprintf() wrapper, not before each individual __()/_e() call

class Parcselect_Label_Email {

	/**
	 * Send label email with PDF attachment and packing list.
	 *
	 * @param int $order_id WooCommerce order ID.
	 * @return bool Whether email was sent.
	 */
	public static function send_label_email( $order_id ) {
		$to = get_option( 'parcselect_label_notify_email', '' );
		if ( empty( $to ) ) {
			$to = get_option( 'admin_email', '' );
		}
		if ( empty( $to ) ) {
			return false;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return false;
		}

		// Cross-install leak guard — never email a customer/admin a label that
		// belongs to a different installation. Returning false here also stops
		// downstream code from reading stale tracking_number / filename meta.
		if ( class_exists( 'Parcselect_Label_Installation' ) && ! Parcselect_Label_Installation::owns( $order ) ) {
			if ( Parcselect_Label_Installation::has_any_label_meta( $order ) ) {
				Parcselect_Label_Installation::purge_order( $order );
			}
			return false;
		}

		$tracking = $order->get_meta( '_ps_label_tracking_number', true );
		$size     = $order->get_meta( '_ps_label_size', true );
		$weight   = $order->get_meta( '_ps_label_weight', true );
		$locker   = $order->get_meta( '_ps_locker_name', true );
		$filename = $order->get_meta( '_ps_label_label_file', true );

		$order_number = $order->get_order_number();
		$receiver     = trim( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name() );

		// Subject.
		/* translators: 1: order number, 2: tracking number */
		$subject = sprintf(
			__( 'Label ready — Order #%1$s — %2$s', 'parcel-selector' ),
			$order_number,
			$tracking ? $tracking : 'N/A'
		);

		// Build HTML body.
		$body = self::build_email_body( $order, $tracking, $size, $weight, $locker, $receiver );

		// Attachments — label PDF.
		$attachments = array();
		if ( ! empty( $filename ) ) {
			$filepath = parcselect_label_storage_dir() . basename( $filename );
			if ( file_exists( $filepath ) ) {
				$attachments[] = $filepath;
			}
		}

		// Send as HTML.
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );

		return wp_mail( $to, $subject, $body, $headers, $attachments );
	}

	/**
	 * Build email body — shipment info + packing list.
	 *
	 * @param WC_Order $order    WooCommerce order.
	 * @param string   $tracking Tracking number.
	 * @param string   $size     Parcel size.
	 * @param string   $weight   Weight in kg.
	 * @param string   $locker   Locker/point ID.
	 * @param string   $receiver Receiver name.
	 * @return string HTML email body.
	 */
	private static function build_email_body( $order, $tracking, $size, $weight, $locker, $receiver ) {
		$order_number = $order->get_order_number();

		$html  = '<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;">';

		// Header.
		$html .= '<div style="background:#2271b1;color:#fff;padding:16px 20px;border-radius:6px 6px 0 0;">';
		$html .= '<h2 style="margin:0;font-size:18px;">';
		/* translators: %s: order number */
		$html .= esc_html( sprintf( __( 'Shipping Label — Order #%s', 'parcel-selector' ), $order_number ) );
		$html .= '</h2></div>';

		// Shipment details.
		$html .= '<div style="border:1px solid #ddd;border-top:0;padding:16px 20px;">';
		$html .= '<h3 style="margin:0 0 12px;font-size:15px;color:#1d2327;">';
		$html .= esc_html__( 'Shipment details', 'parcel-selector' );
		$html .= '</h3>';

		$html .= '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
		$html .= self::email_row( __( 'Tracking number', 'parcel-selector' ), $tracking ? $tracking : '—' );
		$html .= self::email_row( __( 'Receiver', 'parcel-selector' ), $receiver );
		$html .= self::email_row( __( 'Pickup point', 'parcel-selector' ), $locker ? $locker : '—' );
		$html .= self::email_row( __( 'Parcel size', 'parcel-selector' ), $size ? $size : '—' );
		$html .= self::email_row( __( 'Weight', 'parcel-selector' ), $weight ? $weight . ' kg' : '—' );
		$html .= '</table>';
		$html .= '</div>';

		// Packing list — items from order.
		$html .= '<div style="border:1px solid #ddd;border-top:0;padding:16px 20px;">';
		$html .= '<h3 style="margin:0 0 12px;font-size:15px;color:#1d2327;">';
		$html .= esc_html__( 'Packing list', 'parcel-selector' );
		$html .= '</h3>';

		$html .= '<table style="width:100%;border-collapse:collapse;font-size:13px;">';
		$html .= '<tr style="background:#f6f7f7;">';
		$html .= '<th style="text-align:left;padding:8px;border-bottom:2px solid #ddd;">' . esc_html__( 'Product', 'parcel-selector' ) . '</th>';
		$html .= '<th style="text-align:left;padding:8px;border-bottom:2px solid #ddd;">SKU</th>';
		$html .= '<th style="text-align:center;padding:8px;border-bottom:2px solid #ddd;">' . esc_html__( 'Qty', 'parcel-selector' ) . '</th>';
		$html .= '</tr>';

		$items = $order->get_items();
		$row_index = 0;
		foreach ( $items as $item ) {
			$product = $item->get_product();
			$sku     = $product ? $product->get_sku() : '';
			$name    = $item->get_name();
			$qty     = $item->get_quantity();

			$bg = ( $row_index % 2 === 0 ) ? '#fff' : '#f9f9f9';
			$html .= '<tr style="background:' . $bg . ';">';
			$html .= '<td style="padding:6px 8px;border-bottom:1px solid #eee;">' . esc_html( $name ) . '</td>';
			$html .= '<td style="padding:6px 8px;border-bottom:1px solid #eee;color:#666;">' . esc_html( $sku ? $sku : '—' ) . '</td>';
			$html .= '<td style="padding:6px 8px;border-bottom:1px solid #eee;text-align:center;font-weight:700;">' . absint( $qty ) . '</td>';
			$html .= '</tr>';

			// Variation attributes.
			$meta = $item->get_formatted_meta_data( '_', true );
			if ( ! empty( $meta ) ) {
				foreach ( $meta as $meta_item ) {
					$html .= '<tr style="background:' . $bg . ';">';
					$html .= '<td colspan="3" style="padding:2px 8px 6px 24px;font-size:12px;color:#888;">';
					$html .= esc_html( $meta_item->display_key . ': ' . wp_strip_all_tags( $meta_item->display_value ) );
					$html .= '</td></tr>';
				}
			}

			$row_index++;
		}

		$html .= '</table>';

		// Order note (if any customer note).
		$customer_note = $order->get_customer_note();
		if ( ! empty( $customer_note ) ) {
			$html .= '<div style="margin-top:12px;padding:8px 12px;background:#fef9e7;border-left:3px solid #f0a30a;font-size:13px;">';
			$html .= '<strong>' . esc_html__( 'Customer note:', 'parcel-selector' ) . '</strong> ';
			$html .= esc_html( $customer_note );
			$html .= '</div>';
		}

		$html .= '</div>';

		// Footer.
		$html .= '<div style="border:1px solid #ddd;border-top:0;padding:12px 20px;background:#f6f7f7;border-radius:0 0 6px 6px;font-size:11px;color:#999;text-align:center;">';
		$html .= esc_html__( 'Label PDF attached. Generated by the Label tool (ParcelSelector).', 'parcel-selector' );
		$html .= '</div>';

		$html .= '</div>';

		return $html;
	}

	/**
	 * Helper — single row in shipment details table.
	 *
	 * @param string $label Label text.
	 * @param string $value Value text.
	 * @return string HTML table row.
	 */
	private static function email_row( $label, $value ) {
		return '<tr>'
			. '<td style="padding:4px 8px;color:#666;width:140px;">' . esc_html( $label ) . '</td>'
			. '<td style="padding:4px 8px;font-weight:600;">' . esc_html( $value ) . '</td>'
			. '</tr>';
	}
}
