<?php
/**
 * Review request emails — scheduled follow-up after a booking is completed.
 *
 * @package SimplyBuy
 */

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

add_action( 'admin_menu', 'sbuy_register_review_requests_page', 30 );
add_action( 'sbuy_booking_confirmed', 'sbuy_schedule_review_email' );
add_action( 'sbuy_send_review_email', 'sbuy_send_review_email_handler' );

function sbuy_register_review_requests_page(): void {
	add_submenu_page(
		'simply-buy',
		esc_html__( 'Review Requests', 'simply-buy' ),
		esc_html__( 'Review Requests', 'simply-buy' ),
		'manage_options',
		'sbuy-review-requests',
		'sbuy_render_review_requests_page'
	);
}

function sbuy_review_default_settings(): array {
	return array(
		'enabled'     => 0,
		'delay_value' => 24,
		'delay_unit'  => 'hours',
		'subject'     => __( 'How was your experience?', 'simply-buy' ),
		'greeting'    => __( 'Hi [name],', 'simply-buy' ),
		'body_text'   => __( 'thanks for your booking! Would you take a moment to leave us a review?', 'simply-buy' ),
		'reply_to'    => '',
	);
}

function sbuy_render_review_requests_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	if ( ! sbuy_has_pro_access() ) {
		echo '<div class="wrap">';
		echo '<h1>' . esc_html__( 'Review Requests', 'simply-buy' ) . '</h1>';
		echo '<div style="background:#f0f7ff; border-left:4px solid #2271b1; padding:20px; max-width:500px;">';
		echo '<h3>⭐ ' . esc_html__( 'Pro feature', 'simply-buy' ) . '</h3>';
		echo '<p>' . esc_html__( 'Automated customer review requests are available in SimplyBuy Pro.', 'simply-buy' ) . '</p>';
		echo '<a href="' . esc_url( __( 'https://profitclicker.com/pricing/', 'simply-buy' ) ) . '" target="_blank" rel="noopener noreferrer" class="button button-primary">';
		echo esc_html__( 'Upgrade to Pro', 'simply-buy' );
		echo '</a>';
		echo '</div>';
		echo '</div>';
		return;
	}

	$settings = wp_parse_args(
		(array) get_option( 'sbuy_review_request_settings', array() ),
		sbuy_review_default_settings()
	);

	if ( isset( $_POST['sbuy_review_save'] ) && check_admin_referer( 'sbuy_review_save' ) ) {
		$settings = array(
			'enabled'     => isset( $_POST['enabled'] ) ? 1 : 0,
			'delay_value' => max( 1, (int) ( $_POST['delay_value'] ?? 1 ) ),
			'delay_unit'  => in_array( $_POST['delay_unit'] ?? 'hours', array( 'minutes', 'hours', 'days' ), true ) ? $_POST['delay_unit'] : 'hours',
			'subject'     => sanitize_text_field( wp_unslash( $_POST['subject'] ?? '' ) ),
			'greeting'    => sanitize_text_field( wp_unslash( $_POST['greeting'] ?? '' ) ),
			'body_text'   => sanitize_textarea_field( wp_unslash( $_POST['body_text'] ?? '' ) ),
			'reply_to'    => sanitize_email( wp_unslash( $_POST['reply_to'] ?? '' ) ),
		);
		update_option( 'sbuy_review_request_settings', $settings );
		echo '<div class="notice notice-success"><p>' . esc_html__( 'Settings saved.', 'simply-buy' ) . '</p></div>';
	}
	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Review Requests', 'simply-buy' ); ?></h1>

		<div class="notice notice-warning inline"><p>
			<strong><?php esc_html_e( 'Privacy notice:', 'simply-buy' ); ?></strong>
			<?php esc_html_e( 'You as the website operator are responsible for GDPR compliance. Please add a note about review request emails to your privacy policy.', 'simply-buy' ); ?>
		</p></div>

		<form method="post">
			<?php wp_nonce_field( 'sbuy_review_save' ); ?>
			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><?php esc_html_e( 'Enable review request emails', 'simply-buy' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="enabled" value="1" <?php checked( ! empty( $settings['enabled'] ) ); ?>>
							<?php esc_html_e( 'Send a review request after each confirmed booking', 'simply-buy' ); ?>
						</label>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Send after:', 'simply-buy' ); ?></th>
					<td>
						<input type="number" name="delay_value" min="1" step="1" value="<?php echo esc_attr( $settings['delay_value'] ); ?>" style="width:100px;">
						<select name="delay_unit">
							<option value="minutes" <?php selected( $settings['delay_unit'], 'minutes' ); ?>><?php esc_html_e( 'Minutes', 'simply-buy' ); ?></option>
							<option value="hours" <?php selected( $settings['delay_unit'], 'hours' ); ?>><?php esc_html_e( 'Hours', 'simply-buy' ); ?></option>
							<option value="days" <?php selected( $settings['delay_unit'], 'days' ); ?>><?php esc_html_e( 'Days', 'simply-buy' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="sbuy_review_subject"><?php esc_html_e( 'Email subject', 'simply-buy' ); ?></label></th>
					<td><input id="sbuy_review_subject" type="text" name="subject" value="<?php echo esc_attr( $settings['subject'] ); ?>" class="regular-text"></td>
				</tr>
				<tr>
					<th scope="row"><label for="sbuy_review_greeting"><?php esc_html_e( 'Greeting', 'simply-buy' ); ?></label></th>
					<td>
						<input id="sbuy_review_greeting" type="text" name="greeting" value="<?php echo esc_attr( $settings['greeting'] ); ?>" class="regular-text">
						<p class="description"><code>[name]</code> <?php esc_html_e( 'will be replaced with the customer\'s name.', 'simply-buy' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="sbuy_review_body"><?php esc_html_e( 'Message text', 'simply-buy' ); ?></label></th>
					<td>
						<textarea id="sbuy_review_body" name="body_text" rows="6" class="large-text"><?php echo esc_textarea( $settings['body_text'] ); ?></textarea>
						<p class="description"><?php esc_html_e( 'Add your review link directly in the text. The URL is automatically clickable in the email.', 'simply-buy' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="sbuy_review_reply_to"><?php esc_html_e( 'Reply-To Email', 'simply-buy' ); ?></label></th>
					<td><input id="sbuy_review_reply_to" type="email" name="reply_to" value="<?php echo esc_attr( $settings['reply_to'] ); ?>" class="regular-text" placeholder="info@yourcompany.com"></td>
				</tr>
			</table>

			<p>
				<button type="submit" name="sbuy_review_save" class="button button-primary"><?php esc_html_e( 'Save Changes' ); ?></button>
				<button type="button" id="sbuy-review-test-btn" class="button button-secondary" style="margin-left:8px;"><?php esc_html_e( 'Send test email', 'simply-buy' ); ?></button>
				<span id="sbuy-review-test-result" style="margin-left:10px;"></span>
			</p>
		</form>

		<script>
			(function () {
				var btn = document.getElementById('sbuy-review-test-btn');
				var out = document.getElementById('sbuy-review-test-result');
				if (!btn) return;
				var i18n = {
					saving:      <?php echo wp_json_encode( esc_html__( 'Saving…', 'simply-buy' ) ); ?>,
					sendingTest: <?php echo wp_json_encode( esc_html__( 'Sending test…', 'simply-buy' ) ); ?>,
					saveFailed:  <?php echo wp_json_encode( esc_html__( 'Save failed, test email NOT sent.', 'simply-buy' ) ); ?>
				};
				btn.addEventListener('click', async function () {
					btn.disabled = true;
					out.style.color = '#666';
					out.textContent = i18n.saving;

					// 1. Persist the current form so the test email reflects edits.
					try {
						var form = btn.closest('form');
						var formData = new FormData(form);
						formData.set('sbuy_review_save', '1'); // make the save handler fire
						var saveResp = await fetch(window.location.href, {
							method: 'POST', credentials: 'same-origin', body: formData
						});
						if (!saveResp.ok) throw new Error('HTTP ' + saveResp.status);
					} catch (e) {
						out.textContent = i18n.saveFailed + ' (' + e.message + ')';
						out.style.color = '#d63638';
						btn.disabled = false;
						return;
					}

					// 2. Trigger the test email — now reading the just-saved settings.
					out.textContent = i18n.sendingTest;
					try {
						var body = new URLSearchParams({
							action: 'sbuy_review_send_test',
							nonce: <?php echo wp_json_encode( wp_create_nonce( 'simplybuy-nonce' ) ); ?>
						});
						var r = await fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: body });
						var res = await r.json();
						out.textContent = (res && res.data && res.data.message) || '';
						out.style.color = (res && res.success) ? '#1d7302' : '#d63638';
					} catch (e) {
						out.textContent = 'Error';
						out.style.color = '#d63638';
					} finally {
						btn.disabled = false;
					}
				});
			})();
		</script>
	</div>
	<?php
}

/**
 * Scheduled by `sbuy_booking_confirmed`; fires the review email after the configured delay.
 *
 * @param array $booking_data Must contain `name` and `email`.
 */
function sbuy_schedule_review_email( array $booking_data ): void {
	if ( ! sbuy_has_pro_access() ) {
		return;
	}
	$settings = (array) get_option( 'sbuy_review_request_settings', array() );
	if ( empty( $settings['enabled'] ) ) {
		return;
	}
	if ( empty( $booking_data['email'] ) || ! is_email( $booking_data['email'] ) ) {
		return;
	}

	$delay   = max( 1, (int) ( $settings['delay_value'] ?? 1 ) );
	$unit    = $settings['delay_unit'] ?? 'hours';
	$seconds = match ( $unit ) {
		'minutes' => $delay * MINUTE_IN_SECONDS,
		'days'    => $delay * DAY_IN_SECONDS,
		default   => $delay * HOUR_IN_SECONDS,
	};

	wp_schedule_single_event( time() + $seconds, 'sbuy_send_review_email', array( $booking_data ) );
}

function sbuy_send_review_email_handler( array $booking_data ): void {
	sbuy_send_review_email_now( $booking_data );
}

/**
 * Send the review-request email immediately. Used by both the scheduled hook and the test button.
 *
 * @param array $booking_data Must contain `name` and `email`.
 */
function sbuy_send_review_email_now( array $booking_data ): bool {
	$settings = wp_parse_args(
		(array) get_option( 'sbuy_review_request_settings', array() ),
		sbuy_review_default_settings()
	);

	if ( empty( $booking_data['email'] ) || ! is_email( $booking_data['email'] ) ) {
		return false;
	}

	$name     = isset( $booking_data['name'] ) ? (string) $booking_data['name'] : '';
	$greeting = str_replace( '[name]', $name, (string) $settings['greeting'] );
	$unsubscribe_text = __( 'You do not wish to receive further emails? Simply reply with "Unsubscribe".', 'simply-buy' );

	// Plain-text body. Email clients auto-link bare URLs, so the user's
	// review link stays clickable even without HTML formatting.
	$body  = $greeting . "\n\n";
	$body .= wp_strip_all_tags( (string) $settings['body_text'] ) . "\n\n";
	$body .= $unsubscribe_text;

	$from     = get_bloginfo( 'name' );
	$domain   = wp_parse_url( home_url(), PHP_URL_HOST );
	$headers  = array(
		'Content-Type: text/plain; charset=UTF-8',
		"From: $from <no-reply@$domain>",
	);
	if ( ! empty( $settings['reply_to'] ) && is_email( $settings['reply_to'] ) ) {
		$headers[] = 'Reply-To: ' . $settings['reply_to'];
	}

	$sent = wp_mail( $booking_data['email'], $settings['subject'], $body, $headers );

	if ( $sent ) {
		sbuy_add_log( 'review_request', 'Review request email sent to ' . $booking_data['email'] );
	} else {
		sbuy_add_log( 'review_request_error', 'Review request email failed for ' . $booking_data['email'] );
	}

	return (bool) $sent;
}
