<?php
/**
 * Plugin support page — technical issue form (email + WhatsApp).
 *
 * @package SHC4WC
 */

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

class SHC4WC_Support_Settings {
	const DEFAULT_EMAIL    = 'mansoorul.huqq@gmail.com';
	const DEFAULT_WHATSAPP = '923172125955';
	const SUPPORT_FORUM_URL = 'https://wordpress.org/support/plugin/payments-connect-square/';

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ), 11 );
		add_action( 'admin_init', array( $this, 'maybe_handle_submit' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	public static function support_email() {
		if ( defined( 'SHC4WC_SUPPORT_EMAIL' ) && is_email( SHC4WC_SUPPORT_EMAIL ) ) {
			return SHC4WC_SUPPORT_EMAIL;
		}
		return self::DEFAULT_EMAIL;
	}

	public static function whatsapp_number() {
		$number = defined( 'SHC4WC_SUPPORT_WHATSAPP' ) ? SHC4WC_SUPPORT_WHATSAPP : self::DEFAULT_WHATSAPP;
		return preg_replace( '/\D+/', '', (string) $number );
	}

	public static function support_forum_url() {
		if ( defined( 'SHC4WC_SUPPORT_FORUM_URL' ) && filter_var( SHC4WC_SUPPORT_FORUM_URL, FILTER_VALIDATE_URL ) ) {
			return SHC4WC_SUPPORT_FORUM_URL;
		}
		return self::SUPPORT_FORUM_URL;
	}

	public function register_menu() {
		add_submenu_page(
			SHC4WC_Admin_Menu::MENU_SLUG,
			__( 'Support', 'payments-connect-square' ),
			__( 'Support', 'payments-connect-square' ),
			'manage_options',
			SHC4WC_Admin_Menu::SUPPORT_SLUG,
			array( $this, 'render_page' )
		);
	}

	public function enqueue_assets( $hook ) {
		if ( 'payments-square-connect_page_' . SHC4WC_Admin_Menu::SUPPORT_SLUG !== $hook ) {
			return;
		}

		wp_enqueue_script(
			'shc4wc-support-form',
			SHC4WC_PLUGIN_URL . 'assets/js/support-form.js',
			array(),
			SHC4WC_VERSION,
			true
		);

		wp_localize_script(
			'shc4wc-support-form',
			'shc4wcSupport',
			array(
				'whatsappNumber' => self::whatsapp_number(),
				'strings'        => array(
					'fillRequired' => __( 'Please fill in your name, email, and describe the issue before opening WhatsApp.', 'payments-connect-square' ),
				),
			)
		);
	}

	public function maybe_handle_submit() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = (string) filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( SHC4WC_Admin_Menu::SUPPORT_SLUG !== $page ) {
			return;
		}

		if ( ! isset( $_POST['shc4wc_support_submit'] ) ) {
			return;
		}

		check_admin_referer( 'shc4wc_support_request', 'shc4wc_support_nonce' );

		$data = $this->get_submitted_data();
		if ( is_wp_error( $data ) ) {
			wp_safe_redirect(
				SHC4WC_Admin_Menu::page_url(
					SHC4WC_Admin_Menu::SUPPORT_SLUG,
					array( 'status' => 'error' )
				)
			);
			exit;
		}

		$sent = wp_mail(
			self::support_email(),
			$data['mail_subject'],
			$data['mail_body'],
			array(
				'Content-Type: text/plain; charset=UTF-8',
				'Reply-To: ' . $data['name'] . ' <' . $data['email'] . '>',
			)
		);

		wp_safe_redirect(
			SHC4WC_Admin_Menu::page_url(
				SHC4WC_Admin_Menu::SUPPORT_SLUG,
				array( 'status' => $sent ? 'sent' : 'mail_failed' )
			)
		);
		exit;
	}

	/**
	 * @return array<string, string>|WP_Error
	 */
	private function get_submitted_data() {
		$name    = isset( $_POST['shc4wc_support_name'] ) ? sanitize_text_field( wp_unslash( $_POST['shc4wc_support_name'] ) ) : '';
		$email   = isset( $_POST['shc4wc_support_email'] ) ? sanitize_email( wp_unslash( $_POST['shc4wc_support_email'] ) ) : '';
		$issue   = isset( $_POST['shc4wc_support_issue'] ) ? sanitize_key( wp_unslash( $_POST['shc4wc_support_issue'] ) ) : '';
		$subject = isset( $_POST['shc4wc_support_subject'] ) ? sanitize_text_field( wp_unslash( $_POST['shc4wc_support_subject'] ) ) : '';
		$message = isset( $_POST['shc4wc_support_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['shc4wc_support_message'] ) ) : '';

		if ( '' === $name || ! is_email( $email ) || '' === $message ) {
			return new WP_Error( 'invalid', __( 'Missing required fields.', 'payments-connect-square' ) );
		}

		$issue_labels = $this->get_issue_options();
		$issue_label  = isset( $issue_labels[ $issue ] ) ? $issue_labels[ $issue ] : __( 'Other', 'payments-connect-square' );
		if ( '' === $subject ) {
			$subject = $issue_label;
		}

		$context = $this->get_diagnostic_context();

		$mail_subject = sprintf(
			/* translators: 1: site host, 2: issue subject */
			__( '[Payments Square Connect] %1$s — %2$s', 'payments-connect-square' ),
			wp_parse_url( home_url(), PHP_URL_HOST ),
			$subject
		);

		$mail_body = implode(
			"\n",
			array(
				__( 'Support request from Payments Square Connect', 'payments-connect-square' ),
				'',
				__( 'Contact', 'payments-connect-square' ) . ': ' . $name . ' <' . $email . '>',
				__( 'Issue type', 'payments-connect-square' ) . ': ' . $issue_label,
				__( 'Subject', 'payments-connect-square' ) . ': ' . $subject,
				'',
				__( 'Message', 'payments-connect-square' ) . ':',
				$message,
				'',
				'---',
				$context,
			)
		);

		return array(
			'name'         => $name,
			'email'        => $email,
			'subject'      => $subject,
			'issue_label'  => $issue_label,
			'message'      => $message,
			'mail_subject' => $mail_subject,
			'mail_body'    => $mail_body,
			'whatsapp_text' => $this->build_whatsapp_text( $name, $email, $issue_label, $subject, $message, $context ),
		);
	}

	private function build_whatsapp_text( $name, $email, $issue_label, $subject, $message, $context ) {
		return implode(
			"\n",
			array(
				__( 'Payments Square Connect — support request', 'payments-connect-square' ),
				'',
				__( 'Name', 'payments-connect-square' ) . ': ' . $name,
				__( 'Email', 'payments-connect-square' ) . ': ' . $email,
				__( 'Issue type', 'payments-connect-square' ) . ': ' . $issue_label,
				__( 'Subject', 'payments-connect-square' ) . ': ' . $subject,
				'',
				$message,
				'',
				'---',
				$context,
			)
		);
	}

	private function get_diagnostic_context() {
		$settings = SHC4WC_Plugin::get_settings();
		$env      = ! empty( $settings['environment'] ) ? (string) $settings['environment'] : 'unknown';
		$lines    = array(
			__( 'Site diagnostics', 'payments-connect-square' ) . ':',
			__( 'Site URL', 'payments-connect-square' ) . ': ' . home_url(),
			__( 'WordPress', 'payments-connect-square' ) . ': ' . get_bloginfo( 'version' ),
			__( 'Plugin version', 'payments-connect-square' ) . ': ' . SHC4WC_VERSION,
			__( 'Square environment', 'payments-connect-square' ) . ': ' . $env,
			__( 'Square connected', 'payments-connect-square' ) . ': ' . ( SHC4WC_Plugin::has_oauth_connection() ? 'yes' : 'no' ),
			__( 'WooCommerce', 'payments-connect-square' ) . ': ' . ( class_exists( 'WooCommerce' ) ? 'yes' : 'no' ),
			__( 'Contact Form 7', 'payments-connect-square' ) . ': ' . ( defined( 'WPCF7_VERSION' ) ? 'yes' : 'no' ),
		);
		return implode( "\n", $lines );
	}

	/**
	 * @return array<string, string>
	 */
	private function get_issue_options() {
		return array(
			'connect'       => __( 'Square connection / OAuth', 'payments-connect-square' ),
			'checkout'      => __( 'WooCommerce checkout', 'payments-connect-square' ),
			'cf7'           => __( 'Contact Form 7 payment', 'payments-connect-square' ),
			'wpforms'       => __( 'WPForms payment', 'payments-connect-square' ),
			'subscriptions' => __( 'Subscriptions', 'payments-connect-square' ),
			'webhook'       => __( 'Webhooks', 'payments-connect-square' ),
			'other'         => __( 'Other technical issue', 'payments-connect-square' ),
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$user       = wp_get_current_user();
		$name_value = $user && $user->exists() ? $user->display_name : '';
		$email_value = $user && $user->exists() ? $user->user_email : '';

		$this->render_status_notice();
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Support', 'payments-connect-square' ); ?></h1>
			<p><?php esc_html_e( 'Need help with Payments Square Connect? Our technical support team is available 24/7.', 'payments-connect-square' ); ?></p>
			<p>
				<?php
				printf(
					/* translators: %1$s: documentation URL, %2$s: WordPress.org support forum URL. */
					esc_html__( 'Read the %1$s or ask on the %2$s — search existing threads or start a new topic.', 'payments-connect-square' ),
					'<a href="' . esc_url( SHC4WC_Docs::url( '', 'wp_admin_support', 'documentation' ) ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'full documentation', 'payments-connect-square' ) . '</a>',
					'<a href="' . esc_url( self::support_forum_url() ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'WordPress.org Support Forum', 'payments-connect-square' ) . '</a>'
				);
				?>
			</p>
			<p><?php esc_html_e( 'Describe your issue below and send us an email, or open WhatsApp for a faster reply — your message will be pre-filled with site details.', 'payments-connect-square' ); ?></p>

			<form method="post" action="" class="shc4wc-support-form" style="max-width:720px;margin-top:1.5em;">
				<?php wp_nonce_field( 'shc4wc_support_request', 'shc4wc_support_nonce' ); ?>

				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><label for="shc4wc_support_name"><?php esc_html_e( 'Your name', 'payments-connect-square' ); ?></label></th>
						<td><input type="text" class="regular-text" id="shc4wc_support_name" name="shc4wc_support_name" value="<?php echo esc_attr( $name_value ); ?>" required /></td>
					</tr>
					<tr>
						<th scope="row"><label for="shc4wc_support_email"><?php esc_html_e( 'Your email', 'payments-connect-square' ); ?></label></th>
						<td><input type="email" class="regular-text" id="shc4wc_support_email" name="shc4wc_support_email" value="<?php echo esc_attr( $email_value ); ?>" required /></td>
					</tr>
					<tr>
						<th scope="row"><label for="shc4wc_support_issue"><?php esc_html_e( 'Issue type', 'payments-connect-square' ); ?></label></th>
						<td>
							<select id="shc4wc_support_issue" name="shc4wc_support_issue">
								<?php foreach ( $this->get_issue_options() as $key => $label ) : ?>
									<option value="<?php echo esc_attr( $key ); ?>"><?php echo esc_html( $label ); ?></option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="shc4wc_support_subject"><?php esc_html_e( 'Subject', 'payments-connect-square' ); ?></label></th>
						<td>
							<input type="text" class="regular-text" id="shc4wc_support_subject" name="shc4wc_support_subject" placeholder="<?php esc_attr_e( 'Short summary (optional)', 'payments-connect-square' ); ?>" />
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="shc4wc_support_message"><?php esc_html_e( 'Describe the issue', 'payments-connect-square' ); ?></label></th>
						<td>
							<textarea class="large-text" rows="8" id="shc4wc_support_message" name="shc4wc_support_message" required placeholder="<?php esc_attr_e( 'What happened? What did you expect? Steps to reproduce…', 'payments-connect-square' ); ?>"></textarea>
							<p class="description"><?php esc_html_e( 'Site URL, plugin version, and Square connection status are attached automatically.', 'payments-connect-square' ); ?></p>
						</td>
					</tr>
				</table>

				<p class="submit" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
					<button type="submit" name="shc4wc_support_submit" class="button button-primary" value="1">
						<?php esc_html_e( 'Send support email', 'payments-connect-square' ); ?>
					</button>
					<button type="button" class="button" id="shc4wc_support_whatsapp">
						<?php esc_html_e( 'Open WhatsApp', 'payments-connect-square' ); ?>
					</button>
					<a class="button" href="<?php echo esc_url( SHC4WC_Docs::url( '', 'wp_admin_support', 'documentation' ) ); ?>" target="_blank" rel="noopener noreferrer">
						<?php esc_html_e( 'Documentation', 'payments-connect-square' ); ?>
					</a>
					<a class="button" href="<?php echo esc_url( self::support_forum_url() ); ?>" target="_blank" rel="noopener noreferrer">
						<?php esc_html_e( 'Support Forum', 'payments-connect-square' ); ?>
					</a>
				</p>
			</form>

			<p class="description">
				<?php esc_html_e( '24/7 support is available on WhatsApp. For urgent issues, WhatsApp usually gets the quickest response.', 'payments-connect-square' ); ?>
			</p>
		</div>
		<?php
	}

	private function render_status_notice() {
		$status = isset( $_GET['status'] ) ? sanitize_key( wp_unslash( $_GET['status'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( 'sent' === $status ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Support request sent. Our team is available 24/7 and will reply to your email soon.', 'payments-connect-square' ) . '</p></div>';
		} elseif ( 'mail_failed' === $status ) {
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Could not send email from this site. Try Open WhatsApp instead, or check your WordPress mail settings.', 'payments-connect-square' ) . '</p></div>';
		} elseif ( 'error' === $status ) {
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Please fill in all required fields.', 'payments-connect-square' ) . '</p></div>';
		}
	}
}
