<?php
/**
 * Send Email Tool.
 *
 * Send emails using WordPress wp_mail() function with support for HTML content,
 * CC/BCC recipients, and custom headers.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://maximum.software/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

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

/**
 * Send_Email_Tool class.
 */
class Send_Email_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'send_email';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Send Email', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Send an email using WordPress mail system. Supports HTML content and multiple recipients.';
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'to'         => array(
					'type'        => 'string',
					'description' => 'Email recipient(s) in valid email format. Comma-separated for multiple recipients.',
				),
				'subject'    => array(
					'type'        => 'string',
					'description' => 'Email subject line in plain text format.',
				),
				'message'    => array(
					'type'        => 'string',
					'description' => 'Email body content in HTML or plain text format.',
				),
				'from_name'  => array(
					'type'        => 'string',
					'description' => 'Sender name. Default: site name.',
				),
				'from_email' => array(
					'type'        => 'string',
					'description' => 'Sender email address. Default: WordPress admin email.',
					'format'      => 'email',
				),
				'reply_to'   => array(
					'type'        => 'string',
					'description' => 'Reply-to email address.',
					'format'      => 'email',
				),
				'cc'         => array(
					'type'        => 'string',
					'description' => 'CC recipient(s) in valid email format. Comma-separated for multiple.',
				),
				'bcc'        => array(
					'type'        => 'string',
					'description' => 'BCC recipient(s) in valid email format. Comma-separated for multiple.',
				),
				'is_html'    => array(
					'type'        => 'boolean',
					'description' => 'Whether the message is HTML. Default: true.',
				),
			),
			'required'   => array( 'to', 'subject', 'message' ),
		);
	}

	/**
	 * Get the default enabled status for this tool.
	 *
	 * @return bool True if enabled by default, false otherwise.
	 * @since     1.0.0
	 */
	public function get_default_enabled_status() {
		return false;
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		$to      = $args['to'];
		$subject = $args['subject'];
		$message = $args['message'];
		$is_html = $args['is_html'] ?? true;

		// Sanitize from_name to prevent email header injection (strip CRLF).
		$from_name = $args['from_name'] ?? get_bloginfo( 'name' );
		$from_name = str_replace( array( "\r", "\n" ), '', $from_name );

		// Sanitize from_email to prevent header injection.
		$from_email = sanitize_email( $args['from_email'] ?? get_option( 'admin_email' ) );
		if ( empty( $from_email ) ) {
			return $this->error_response( 'Invalid from_email address' );
		}

		$headers = array();

		if ( $is_html ) {
			$headers[] = 'Content-Type: text/html; charset=UTF-8';
		}

		$headers[] = "From: {$from_name} <{$from_email}>";

		// Sanitize reply_to email.
		if ( ! empty( $args['reply_to'] ) ) {
			$reply_to = sanitize_email( $args['reply_to'] );
			if ( ! empty( $reply_to ) ) {
				$headers[] = 'Reply-To: ' . $reply_to;
			}
		}

		// Sanitize CC emails.
		if ( ! empty( $args['cc'] ) ) {
			$cc_addresses = array_map( 'trim', explode( ',', $args['cc'] ) );
			foreach ( $cc_addresses as $cc ) {
				$cc = sanitize_email( $cc );
				if ( ! empty( $cc ) ) {
					$headers[] = 'Cc: ' . $cc;
				}
			}
		}

		// Sanitize BCC emails.
		if ( ! empty( $args['bcc'] ) ) {
			$bcc_addresses = array_map( 'trim', explode( ',', $args['bcc'] ) );
			foreach ( $bcc_addresses as $bcc ) {
				$bcc = sanitize_email( $bcc );
				if ( ! empty( $bcc ) ) {
					$headers[] = 'Bcc: ' . $bcc;
				}
			}
		}

		// Sanitize recipient emails.
		$recipients = array();
		foreach ( array_map( 'trim', explode( ',', $to ) ) as $recipient ) {
			$sanitized = sanitize_email( $recipient );
			if ( ! empty( $sanitized ) ) {
				$recipients[] = $sanitized;
			}
		}

		if ( empty( $recipients ) ) {
			return $this->error_response( 'No valid recipient email addresses' );
		}

		$result = wp_mail( $recipients, $subject, $message, $headers );

		if ( ! $result ) {
			return $this->error_response( 'Failed to send email. Check WordPress mail configuration.' );
		}

		return $this->success_response(
			'Email sent successfully',
			array(
				'to'      => $recipients,
				'subject' => $subject,
				'from'    => "{$from_name} <{$from_email}>",
				'is_html' => $is_html,
			)
		);
	}
}
