<?php
/**
 * Admin Support Page
 *
 * @package minimalblog
 */

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

define( 'MINIMALBLOG_SUPPORT_EMAIL', 'contact@falselogics.com' );

/**
 * Register support page under Appearance.
 */
function minimalblog_register_support_page() {
	add_theme_page(
		esc_html__( 'MinimalBlog Support', 'minimalblog' ),
		esc_html__( 'MinimalBlog Support', 'minimalblog' ),
		'edit_theme_options',
		'minimalblog-support',
		'minimalblog_render_support_page'
	);
}
add_action( 'admin_menu', 'minimalblog_register_support_page' );

/**
 * Enqueue support assets in wp-admin.
 */
function minimalblog_enqueue_support_assets() {
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		return;
	}

	wp_enqueue_style(
		'minimalblog-admin-support',
		get_theme_file_uri( '/inc/admin-support.css' ),
		array(),
		wp_get_theme()->get( 'Version' )
	);
	wp_enqueue_script(
		'minimalblog-admin-support',
		get_theme_file_uri( '/inc/admin-support.js' ),
		array( 'jquery' ),
		wp_get_theme()->get( 'Version' ),
		true
	);
	wp_localize_script(
		'minimalblog-admin-support',
		'minimalblogSupport',
		array(
			'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
			'nonce'       => wp_create_nonce( 'minimalblog_support_nonce' ),
			'sendingText' => esc_html__( 'Sending...', 'minimalblog' ),
			'failedText'  => esc_html__( 'Failed to send. Please try again.', 'minimalblog' ),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'minimalblog_enqueue_support_assets' );

/**
 * Render support page.
 */
function minimalblog_render_support_page() {
	?>
		<div class="wrap minimalblog-support-page">
			<h1><?php esc_html_e( 'MinimalBlog Support', 'minimalblog' ); ?></h1>
			<div class="minimalblog-support-intro">
				<p class="description">
					<?php esc_html_e( 'Need help or customization? Contact the author using the form below or email us directly.', 'minimalblog' ); ?>
				</p>
				<p class="minimalblog-support-email">
					<strong><?php esc_html_e( 'Direct Email:', 'minimalblog' ); ?></strong>
					<a href="mailto:<?php echo esc_attr( MINIMALBLOG_SUPPORT_EMAIL ); ?>">
						<?php echo esc_html( MINIMALBLOG_SUPPORT_EMAIL ); ?>
					</a>
				</p>
				<button type="button" class="button button-primary minimalblog-open-support">
					<?php esc_html_e( 'Contact Support', 'minimalblog' ); ?>
				</button>
			</div>
		</div>
	<?php
}

/**
 * Render global support launcher and modal in admin footer.
 */
function minimalblog_render_admin_support_modal() {
	if ( ! current_user_can( 'edit_theme_options' ) ) {
		return;
	}
	?>
	<div class="minimalblog-support-launcher-wrap">
		<button type="button" class="minimalblog-support-launcher minimalblog-open-support" aria-label="<?php esc_attr_e( 'Open support form', 'minimalblog' ); ?>">
			<span class="dashicons dashicons-sos" aria-hidden="true"></span>
			<span><?php esc_html_e( 'Support', 'minimalblog' ); ?></span>
		</button>
	</div>

	<div id="minimalblog-support-modal" class="minimalblog-support-modal" aria-hidden="true">
		<div class="minimalblog-support-modal__backdrop" data-minimalblog-support-close></div>
		<div class="minimalblog-support-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="minimalblog-support-title" aria-describedby="minimalblog-support-help" tabindex="-1">
			<div class="minimalblog-support-modal__header">
				<h2 id="minimalblog-support-title"><?php esc_html_e( 'Contact Support', 'minimalblog' ); ?></h2>
				<button type="button" class="minimalblog-support-modal__close" aria-label="<?php esc_attr_e( 'Close', 'minimalblog' ); ?>" data-minimalblog-support-close>×</button>
			</div>
			<form id="minimalblog-support-form">
				<div class="minimalblog-support-modal__body">
					<p id="minimalblog-support-help" class="description">
						<?php esc_html_e( 'Please include enough detail so we can reproduce and solve your issue quickly.', 'minimalblog' ); ?>
					</p>
					<div class="minimalblog-support-grid">
						<div>
							<label for="minimalblog-support-name"><?php esc_html_e( 'Name', 'minimalblog' ); ?></label>
							<input type="text" id="minimalblog-support-name" name="name" class="regular-text" autocomplete="name" required>
						</div>
						<div>
							<label for="minimalblog-support-email"><?php esc_html_e( 'Email', 'minimalblog' ); ?></label>
							<input type="email" id="minimalblog-support-email" name="email" class="regular-text" autocomplete="email" required>
						</div>
					</div>

					<label for="minimalblog-support-subject"><?php esc_html_e( 'Subject', 'minimalblog' ); ?></label>
					<input type="text" id="minimalblog-support-subject" name="subject" class="regular-text" required>

					<label for="minimalblog-support-message"><?php esc_html_e( 'Message', 'minimalblog' ); ?></label>
					<textarea id="minimalblog-support-message" name="message" rows="6" class="large-text" required></textarea>

					<div class="minimalblog-support-modal__status" id="minimalblog-support-status" aria-live="polite" role="status"></div>
				</div>
				<div class="minimalblog-support-modal__footer">
					<button type="submit" class="button button-primary" id="minimalblog-support-submit">
						<?php esc_html_e( 'Send Message', 'minimalblog' ); ?>
					</button>
					<button type="button" class="button" data-minimalblog-support-close>
						<?php esc_html_e( 'Cancel', 'minimalblog' ); ?>
					</button>
				</div>
			</form>
		</div>
	</div>
	<?php
}
add_action( 'admin_footer', 'minimalblog_render_admin_support_modal' );

/**
 * AJAX: Send support message.
 */
function minimalblog_send_support_message() {
	check_ajax_referer( 'minimalblog_support_nonce', 'nonce' );

	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Insufficient permissions.', 'minimalblog' ) ), 403 );
	}

	$name    = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
	$email   = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
	$subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
	$message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';

	if ( empty( $name ) || empty( $email ) || empty( $subject ) || empty( $message ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'All fields are required.', 'minimalblog' ) ), 400 );
	}
	if ( ! is_email( $email ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Please enter a valid email address.', 'minimalblog' ) ), 400 );
	}

	$current_user = wp_get_current_user();
	$site_name    = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
	$site_url     = home_url( '/' );
	$theme        = wp_get_theme();
	$wp_version   = get_bloginfo( 'version' );
	$php_version  = PHP_VERSION;
	$locale       = get_locale();
	$admin_email  = get_option( 'admin_email' );

	$full_subject = sprintf( '[%s] %s', $site_name, $subject );
	$body         = "Name: {$name}\n";
	$body        .= "Email: {$email}\n";
	$body        .= "User: {$current_user->user_login}\n";
	$body        .= "Site: {$site_url}\n\n";
	$body        .= "Theme: {$theme->get( 'Name' )} {$theme->get( 'Version' )}\n";
	$body        .= "WordPress: {$wp_version}\n";
	$body        .= "PHP: {$php_version}\n";
	$body        .= "Locale: {$locale}\n";
	$body        .= "Admin Email: {$admin_email}\n\n";
	$body        .= "Message:\n{$message}\n";

	$headers = array(
		'Content-Type: text/plain; charset=UTF-8',
		'Reply-To: ' . $name . ' <' . $email . '>',
	);

	$sent = wp_mail( MINIMALBLOG_SUPPORT_EMAIL, $full_subject, $body, $headers );

	if ( ! $sent ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Failed to send. Please try again later.', 'minimalblog' ) ), 500 );
	}

	wp_send_json_success( array( 'message' => esc_html__( 'Message sent successfully.', 'minimalblog' ) ) );
}
add_action( 'wp_ajax_minimalblog_support_send', 'minimalblog_send_support_message' );
