<?php
/**
 * Email Sender
 *
 * Sends receipt emails with PDF attachments.
 *
 * @package DonorCore\Receipts
 */

namespace DonorCore\Receipts;

defined( 'ABSPATH' ) || exit;

/**
 * Email Sender Class
 */
class Email_Sender {

	/**
	 * Send receipt email.
	 *
	 * @param int    $order_id  Order ID.
	 * @param string $file_path PDF file path.
	 * @return bool
	 */
	public function send_receipt_email( $order_id, $file_path ) {
		$order = wc_get_order( $order_id );

		if ( ! $order || ! file_exists( $file_path ) ) {
			return false;
		}

		// Get customer billing email (NOT admin email)
		$to = $order->get_billing_email();
		
		// Get custom subject or use default
		$subject = $this->get_email_subject();
		$subject = $this->replace_placeholders( $subject, $order );
		
		// Set proper headers with From address
		$from_email = get_option( 'admin_email' );
		$from_name  = get_bloginfo( 'name' );
		
		$headers = array(
			'Content-Type: text/html; charset=UTF-8',
			sprintf( 'From: %s <%s>', $from_name, $from_email ),
		);

		$message = $this->get_email_template( $order );
		
		
		// Prevent any filters from changing the recipient
		add_filter( 'wp_mail', function( $args ) use ( $to ) {
			$args['to'] = $to; // Force recipient to be customer email
			return $args;
		}, 999 );
		
		// Disable admin notification for this specific email
		add_filter( 'wp_mail_from', function() use ( $from_email ) {
			return $from_email;
		}, 999 );
		
		// Remove any BCC/CC to admin
		add_filter( 'wp_mail_content_type', function() {
			return 'text/html';
		}, 999 );
		
		// Prevent WooCommerce from adding admin as recipient
		remove_all_filters( 'woocommerce_email_recipient_customer_processing_order' );
		remove_all_filters( 'woocommerce_email_recipient_customer_completed_order' );

		$sent = wp_mail( $to, $subject, $message, $headers, array( $file_path ) );

		if ( $sent ) {
			$order->add_order_note( 
				sprintf( 
					/* translators: %s: email address */
					__( 'Donation receipt sent via email to %s', 'donorcore-donations' ),
					$to
				) 
			);
		}

		return $sent;
	}

	/**
	 * Get email subject line.
	 *
	 * @return string
	 */
	private function get_email_subject() {
		$subject = sanitize_text_field( get_option( 'donorcore_email_subject', '' ) );
		
		if ( empty( $subject ) ) {
			/* translators: %s: site name */
			$subject = sprintf( __( 'Your Donation Receipt from %s', 'donorcore-donations' ), '{site_name}' );
		}
		
		return $subject;
	}

	/**
	 * Get email HTML template.
	 *
	 * @param \WC_Order $order Order object.
	 * @return string
	 */
	private function get_email_template( $order ) {
		// Get saved template from settings
		$template = wp_kses_post( get_option( 'donorcore_email_template', '' ) );
		
		// If no custom template, load default
		if ( empty( $template ) ) {
			$template = $this->get_default_email_template();
		}
		
		// Replace placeholders with actual values
		return $this->replace_placeholders( $template, $order );
	}

	/**
	 * Get default email template.
	 *
	 * @return string
	 */
	private function get_default_email_template() {
		$template_file = DONOR_CORE_PLUGIN_DIR . 'includes/Receipts/templates/email-default.html';
		
		if ( file_exists( $template_file ) ) {
			return file_get_contents( $template_file );
		}
		
		// Fallback if file doesn't exist
		return '<html><body><h1>Thank You for Your Donation!</h1><p>Amount: {amount}</p></body></html>';
	}

	/**
	 * Replace placeholders with actual values.
	 *
	 * @param string    $template Template content.
	 * @param \WC_Order $order    Order object.
	 * @return string
	 */
	private function replace_placeholders( $template, $order ) {
		// Get donation details
		$amount      = 0;
		$campaign    = 'General Donation';
		$campaign_id = 0;

		foreach ( $order->get_items() as $item ) {
			$amount      = $item->get_meta( '_donorcore_donation_amount', true ) ?: $item->get_total();
			$campaign_id = $item->get_meta( '_donorcore_campaign_id', true );
			break;
		}

		if ( $campaign_id ) {
			$campaign_post = get_post( $campaign_id );
			$campaign      = $campaign_post ? $campaign_post->post_title : $campaign;
		}

		// Get site logo
		$logo_id  = get_theme_mod( 'custom_logo' );
		$logo_src = $logo_id ? wp_get_attachment_image_src( $logo_id, 'full' ) : false;
		$logo_tag = $logo_src ? '<img src="' . esc_url( $logo_src[0] ) . '" alt="' . esc_attr( get_bloginfo( 'name' ) ) . '" style="max-width: 200px; height: auto;" />' : '';

		// Build placeholders array
		$placeholders = array(
			'{donor_name}'       => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
			'{donor_first_name}' => $order->get_billing_first_name(),
			'{donor_last_name}'  => $order->get_billing_last_name(),
			'{donor_email}'      => $order->get_billing_email(),
			'{amount}'           => wc_price( $amount ),
			'{campaign}'         => esc_html( $campaign ),
			'{date}'             => $order->get_date_created()->format( 'F j, Y' ),
			'{order_id}'         => $order->get_id(),
			'{site_name}'        => get_bloginfo( 'name' ),
			'{site_url}'         => home_url(),
			'{site_logo}'        => $logo_tag,
		);

		// Replace all placeholders
		return str_replace( array_keys( $placeholders ), array_values( $placeholders ), $template );
	}
}
