<?php
/**
 * Help Email Handler for Author Kit.
 *
 * Defines the Author_Kit_Help_Email class to process AJAX help form submissions,
 * validate input, handle file uploads, and send support emails.
 *
 * @package Author_Kit
 * @since 1.0.0
 */

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

/**
 * Handles the support/help email functionality for the Author Kit plugin.
 *
 * Registers the AJAX callback and processes help form submissions,
 * including file uploads and email sending.
 */
class Author_Kit_Help_Email {

	/**
	 * Registers AJAX handler for help email form.
	 *
	 * Hooks the help form submission to its callback method.
	 *
	 * @return void
	 */
	public function __construct() {
		add_action( 'wp_ajax_author_kit_help_email', array( $this, 'author_kit_handle_help_email' ) );
	}


	/**
	 * Handles AJAX request to send help form email.
	 *
	 * Validates nonce and required fields, sanitizes input,
	 * processes file uploads, and sends an email with attachments.
	 *
	 * @return void Sends JSON success or error response.
	 */
	public function author_kit_handle_help_email() {
		check_ajax_referer( 'author-kit-help-nonce', 'nonce' );

		// Sanitize and extract POST data.
		$name    = sanitize_text_field( wp_unslash( $_POST['help_name'] ?? '' ) );
		$email   = sanitize_email( wp_unslash( $_POST['help_email'] ?? '' ) );
		$subject = sanitize_text_field( wp_unslash( $_POST['help_subject'] ?? '' ) );
		$message = sanitize_textarea_field( wp_unslash( $_POST['help_message'] ?? '' ) );
		$privacy = isset( $_POST['privacy_check'] ) ? sanitize_text_field( wp_unslash( $_POST['privacy_check'] ) ) : '';

		// Validate required fields.
		if ( empty( $name ) || empty( $email ) || empty( $subject ) || empty( $message ) ) {
			wp_send_json_error( array( 'message' => __( 'Please fill in all required fields.', 'author-kit' ) ) );
		}

		if ( ! is_email( $email ) ) {
			wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'author-kit' ) ) );
		}

		if ( empty( $privacy ) ) {
			wp_send_json_error( array( 'message' => __( 'Please accept the privacy policy.', 'author-kit' ) ) );
		}

		// Email body.
		$body  = "Name: $name\n";
		$body .= "Email: $email\n";
		$body .= "Subject: $subject\n\n";
		$body .= "Message:\n$message\n";

		$to          = 'authorkit.wp@gmail.com';
		$headers     = array( 'From: ' . $name . ' <' . $email . '>' );
		$attachments = array();

		$filenames_array = isset( $_FILES['help_file']['name'] ) && is_array( $_FILES['help_file']['name'] ) ? array_map( 'sanitize_file_name', $_FILES['help_file']['name'] ) : array();

		// Handle file uploads.
		if ( ! empty( $_FILES['help_file'] ) && ! empty( $filenames_array ) ) {
			foreach ( $filenames_array as $key => $filename ) {
				if (
					isset( $_FILES['help_file']['error'][ $key ] ) &&
					UPLOAD_ERR_OK === $_FILES['help_file']['error'][ $key ] &&
					isset(
						$_FILES['help_file']['type'][ $key ],
						$_FILES['help_file']['tmp_name'][ $key ],
						$_FILES['help_file']['size'][ $key ]
					)
				) {
					$file_array = array(
						'name'     => sanitize_file_name( $filename ),
						'type'     => sanitize_mime_type( $_FILES['help_file']['type'][ $key ] ),
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
						'tmp_name' => $_FILES['help_file']['tmp_name'][ $key ], // tmp_name is system-generated and doesn't need sanitization.
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
						'error'    => $_FILES['help_file']['error'][ $key ], // error is system-generated and doesn't need sanitization and already validated via UPLOAD_ERR_OK.
						'size'     => absint( $_FILES['help_file']['size'][ $key ] ),
					);

					$upload = wp_handle_upload( $file_array, array( 'test_form' => false ) );

					if ( ! isset( $upload['error'] ) ) {
						$attachments[] = $upload['file'];
					} else {
						wp_send_json_error( array( 'message' => $upload['error'] ) );
					}
				}
			}
		}

		// Send email.
		$sent = wp_mail( $to, $subject, $body, $headers, $attachments );

		if ( $sent ) {
			wp_send_json_success( array( 'message' => __( 'Your message has been sent successfully.', 'author-kit' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to send email. Please try again later.', 'author-kit' ) ) );
		}
	}
}

new Author_Kit_Help_Email();
