<?php
/**
 * Quote form class file.
 *
 * @package WholesaleNode_For_WooCommerce
 */

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

/**
 * Renders the quote request form and handles submissions.
 */
class WOOWSNFree_Quotes {

	private static $_instance = null;

	/** @var array Quote display settings. */
	private $settings = array();

	/**
	 * @return self
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	private function __construct() {
		$this->settings = $this->load_settings();
		$this->hooks();
	}

	/**
	 * Load settings.
	 *
	 * @return array
	 */
	private function load_settings() {
		$defaults = array(
			'require_login'            => false,
			'send_quote_notifications' => true,
			'quote_notification_email' => '',
			'show_product_selection'   => true,
			'enableOnSingleProduct'    => true,
			'displayPosition'          => 'after_add_to_cart_button',
			'displayMode'              => 'popup',
			'popupButtonText'          => __( 'Request a Quote', 'wholesalenode-for-woocommerce' ),
			'popupButtonClass'         => '',
		);

		$all    = get_option( 'woowsn_free_settings_all', array() );
		$quotes = isset( $all['quotes'] ) ? (array) $all['quotes'] : array();
		$merged = array_merge( $defaults, array_filter( $quotes, function( $v ) { return $v !== '' && $v !== null; } ) );

		$form_opt = get_option( 'woowsn_quote_form', array() );
		if ( ! empty( $form_opt['settings'] ) && is_array( $form_opt['settings'] ) ) {
			foreach ( array( 'displayMode', 'popupButtonText', 'popupButtonClass', 'enableOnSingleProduct', 'displayPosition' ) as $k ) {
				if ( isset( $form_opt['settings'][ $k ] ) && $form_opt['settings'][ $k ] !== '' && $form_opt['settings'][ $k ] !== null ) {
					$merged[ $k ] = $form_opt['settings'][ $k ];
				}
			}
		}

		$pro_opt = get_option( 'woowsn_quotes_settings', array() );
		if ( ! empty( $pro_opt ) && is_array( $pro_opt ) ) {
			$pro_map = array(
				'displayMode'      => array( 'displaymode', 'displayMode' ),
				'displayPosition'  => array( 'displayposition', 'displayPosition' ),
				'popupButtonText'  => array( 'popupbuttontext', 'popupButtonText' ),
				'popupButtonClass' => array( 'popupbuttonclass', 'popupButtonClass' ),
			);
			foreach ( $pro_map as $local_key => $pro_keys ) {
				foreach ( $pro_keys as $pk ) {
					if ( isset( $pro_opt[ $pk ] ) && $pro_opt[ $pk ] !== '' ) {
						$merged[ $local_key ] = $pro_opt[ $pk ];
						break;
					}
				}
			}
		}

		if ( empty( $merged['popupButtonText'] ) ) {
			$merged['popupButtonText'] = __( 'Request a Quote', 'wholesalenode-for-woocommerce' );
		}

		return $merged;
	}

	/**
	 * Attach hooks.
	 */
	private function hooks() {
		add_shortcode( 'woowsn_quote_form', array( $this, 'render_shortcode' ) );
		add_action( 'wp_ajax_woowsn_free_submit_quote',           array( $this, 'handle_submission' ) );
		add_action( 'wp_ajax_nopriv_woowsn_free_submit_quote',    array( $this, 'handle_submission' ) );
		add_action( 'wp_ajax_woowsn_free_product_search',         array( $this, 'ajax_product_search' ) );
		add_action( 'wp_ajax_nopriv_woowsn_free_product_search',  array( $this, 'ajax_product_search' ) );
		add_action( 'wp_enqueue_scripts',                         array( $this, 'maybe_enqueue' ) );

		if ( ! empty( $this->settings['enableOnSingleProduct'] ) ) {
			$position = $this->settings['displayPosition'] ?: 'after_add_to_cart_button';
			$hook     = 'woocommerce_' . $position;
			add_action( $hook, array( $this, 'render_on_product_page' ), 20 );
		}
	}

	/**
	 * Render the quote form on a single product page.
	 */
	public function render_on_product_page() {
		if ( ! is_singular( 'product' ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $this->build_form( get_the_ID() );
	}

	/**
	 * Enqueue JS/CSS on pages that use the shortcode or on product pages.
	 */
	public function maybe_enqueue() {
		global $post;
		$needs_form = (
			( $post && has_shortcode( $post->post_content, 'woowsn_quote_form' ) )
			|| ( ! empty( $this->settings['enableOnSingleProduct'] ) && is_singular( 'product' ) )
		);

		if ( ! $needs_form ) {
			return;
		}

		wp_enqueue_script(
			'woowsn-free-quote',
			WOOWSN_FREE_URL . 'assets/js/quote-form.js',
			array( 'jquery' ),
			WOOWSN_FREE_VERSION,
			true
		);
		wp_localize_script( 'woowsn-free-quote', 'woowsnFreeQuote', array(
			'ajaxurl'           => admin_url( 'admin-ajax.php' ),
			'nonce'             => wp_create_nonce( 'woowsn_free_quote' ),
			'product_search_nonce' => wp_create_nonce( 'woowsn_free_product_search' ),
			'current_product_id'   => is_singular( 'product' ) ? get_the_ID() : 0,
			'is_product_page'      => is_singular( 'product' ),
			'display_mode'         => $this->settings['displayMode'] ?? 'inline',
			'popup_button_text'    => $this->settings['popupButtonText'] ?? '',
			'popup_button_class'   => $this->settings['popupButtonClass'] ?? '',
			'i18n'              => array(
				'success'         => __( 'Your quote request has been submitted. We will be in touch shortly.', 'wholesalenode-for-woocommerce' ),
				'error'           => __( 'There was an error submitting your request. Please try again.', 'wholesalenode-for-woocommerce' ),
				'sending'         => __( 'Sending\u2026', 'wholesalenode-for-woocommerce' ),
				'submit'          => __( 'Submit Request', 'wholesalenode-for-woocommerce' ),
				'search_product'  => __( 'Search for a product...', 'wholesalenode-for-woocommerce' ),
				'no_results'      => __( 'No products found', 'wholesalenode-for-woocommerce' ),
				'searching'       => __( 'Searching...', 'wholesalenode-for-woocommerce' ),
			),
		) );
		wp_enqueue_style(
			'woowsn-free-frontend',
			WOOWSN_FREE_URL . 'assets/css/frontend.css',
			array(),
			WOOWSN_FREE_VERSION
		);
	}

	/**
	 * [woowsn_quote_form] shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string
	 */
	public function render_shortcode( $atts = array() ) {
		$atts = shortcode_atts(
			array(
				'product_id' => 0,
				'popup'      => '',
			),
			$atts,
			'woowsn_quote_form'
		);

		if ( ! wp_script_is( 'woowsn-free-quote', 'enqueued' ) ) {
			$this->maybe_enqueue();
		}

		return $this->build_form( absint( $atts['product_id'] ) );
	}

	/**
	 * Build the quote form HTML using the same markup structure as the pro plugin.
	 *
	 * @param int $product_id Current product ID.
	 * @return string
	 */
	private function build_form( $product_id = 0 ) {
		$require_login = ! empty( $this->settings['require_login'] );
		if ( $require_login && ! is_user_logged_in() ) {
			return '<p class="woowsn-free-login-notice">'
				. sprintf(
					/* translators: %s: login URL */
					wp_kses( __( 'Please <a href="%s">log in</a> to request a quote.', 'wholesalenode-for-woocommerce' ), array( 'a' => array( 'href' => array() ) ) ),
					esc_url( wc_get_page_permalink( 'myaccount' ) )
				)
				. '</p>';
		}

		$user  = wp_get_current_user();
		$name  = $user->ID ? $user->display_name : '';
		$email = $user->ID ? $user->user_email   : '';

		$show_product_field = ! empty( $this->settings['show_product_selection'] ) && ! $product_id;
		$display_mode       = $this->settings['displayMode'] ?? 'popup';
		$is_popup           = ( 'popup' === $display_mode );
		$btn_text           = ! empty( $this->settings['popupButtonText'] ) ? $this->settings['popupButtonText'] : __( 'Request a Quote', 'wholesalenode-for-woocommerce' );
		$btn_class          = esc_attr( $this->settings['popupButtonClass'] ?? '' );
		$form_uid           = 'woowsn-quote-form-' . uniqid();

		ob_start();

		if ( $is_popup ) :
			?>
			<div class="woowsn-quote-popup-trigger-wrap">
				<button type="button" class="woowsn-quote-popup-btn <?php echo esc_attr( $btn_class ); ?>" data-woowsn-popup="<?php echo esc_attr( $form_uid ); ?>">
					<?php echo esc_html( $btn_text ); ?>
				</button>
			</div>
			<div class="woowsn-quote-popup-overlay" id="<?php echo esc_attr( $form_uid ); ?>-overlay" style="display:none;">
				<div class="woowsn-quote-popup-modal">
					<button type="button" class="woowsn-quote-popup-close" data-woowsn-popup-close="<?php echo esc_attr( $form_uid ); ?>">&times;</button>
		<?php endif; ?>

		<div class="woowsn-quote-form-wrapper <?php echo esc_attr( $is_popup ? 'woowsn-quote-form-popup' : '' ); ?>" id="<?php echo esc_attr( $form_uid ); ?>">
			<h3 class="woowsn-quote-title"><?php esc_html_e( 'Request a Quote', 'wholesalenode-for-woocommerce' ); ?></h3>

			<div class="woowsn-quote-messages" style="display:none;"></div>

			<div class="woowsn-free-quote-form">
				<input type="hidden" name="action" value="woowsn_free_submit_quote">
				<input type="hidden" name="nonce" value="<?php echo esc_attr( wp_create_nonce( 'woowsn_free_quote' ) ); ?>">
				<?php if ( $product_id ) : ?>
					<input type="hidden" name="current_product_id" value="<?php echo esc_attr( $product_id ); ?>">
				<?php endif; ?>

				<div class="woowsn-quote-field required">
					<label for="woowsnq_name_<?php echo esc_attr( $form_uid ); ?>"><?php esc_html_e( 'Your Name', 'wholesalenode-for-woocommerce' ); ?></label>
					<input type="text" id="woowsnq_name_<?php echo esc_attr( $form_uid ); ?>" name="customer_name" value="<?php echo esc_attr( $name ); ?>" required>
				</div>

				<div class="woowsn-quote-field required">
					<label for="woowsnq_email_<?php echo esc_attr( $form_uid ); ?>"><?php esc_html_e( 'Email Address', 'wholesalenode-for-woocommerce' ); ?></label>
					<input type="email" id="woowsnq_email_<?php echo esc_attr( $form_uid ); ?>" name="customer_email" value="<?php echo esc_attr( $email ); ?>" required>
				</div>

				<div class="woowsn-quote-field">
					<label for="woowsnq_phone_<?php echo esc_attr( $form_uid ); ?>"><?php esc_html_e( 'Phone', 'wholesalenode-for-woocommerce' ); ?></label>
					<input type="tel" id="woowsnq_phone_<?php echo esc_attr( $form_uid ); ?>" name="customer_phone">
				</div>

				<?php if ( $show_product_field ) : ?>
				<div class="woowsn-quote-field required">
					<label for="woowsnq_product_<?php echo esc_attr( $form_uid ); ?>"><?php esc_html_e( 'Product', 'wholesalenode-for-woocommerce' ); ?></label>
					<select id="woowsnq_product_<?php echo esc_attr( $form_uid ); ?>" name="current_product_id" class="woowsn-free-ps-select" required>
						<option value=""><?php esc_html_e( 'Search for a product...', 'wholesalenode-for-woocommerce' ); ?></option>
					</select>
				</div>
				<?php endif; ?>

				<div class="woowsn-quote-field">
					<label for="woowsnq_quantity_<?php echo esc_attr( $form_uid ); ?>"><?php esc_html_e( 'Quantity', 'wholesalenode-for-woocommerce' ); ?></label>
					<input type="number" id="woowsnq_quantity_<?php echo esc_attr( $form_uid ); ?>" name="quantity" min="1" value="1">
				</div>

				<div class="woowsn-quote-field">
					<label for="woowsnq_message_<?php echo esc_attr( $form_uid ); ?>"><?php esc_html_e( 'Message', 'wholesalenode-for-woocommerce' ); ?></label>
					<textarea id="woowsnq_message_<?php echo esc_attr( $form_uid ); ?>" name="quote_message" rows="4"></textarea>
				</div>

				<div class="woowsn-quote-submit-wrapper">
					<button type="button" class="woowsn-quote-submit">
						<span class="submit-text"><?php esc_html_e( 'Submit Request', 'wholesalenode-for-woocommerce' ); ?></span>
						<span class="submit-loading" style="display:none;"><?php esc_html_e( 'Submitting…', 'wholesalenode-for-woocommerce' ); ?></span>
					</button>
				</div>
			</div>
		</div>

		<?php if ( $is_popup ) : ?>
				</div><!-- .woowsn-quote-popup-modal -->
			</div><!-- .woowsn-quote-popup-overlay -->
		<?php endif; ?>

		<?php
		return ob_get_clean();
	}

	/**
	 * Handle AJAX product search for the quote form product selection field.
	 */
	public function ajax_product_search() {
		if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'woowsn_free_product_search' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'wholesalenode-for-woocommerce' ) ), 403 );
		}

		$term = sanitize_text_field( wp_unslash( $_GET['term'] ?? '' ) );
		if ( strlen( $term ) < 2 || ! function_exists( 'wc_get_products' ) ) {
			wp_send_json_success( array() );
		}

		$products = wc_get_products( array(
			'limit'   => 15,
			'status'  => 'publish',
			's'       => $term,
			'return'  => 'objects',
		) );

		$data = array();
		foreach ( $products as $product ) {
			$data[] = array(
				'id'  => $product->get_id(),
				'name' => $product->get_name(),
				'sku'  => $product->get_sku(),
			);
		}

		wp_send_json_success( $data );
	}

	/**
	 * Handle AJAX quote form submission.
	 */
	public function handle_submission() {
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'woowsn_free_quote' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh and try again.', 'wholesalenode-for-woocommerce' ) ), 403 );
		}

		$customer_name  = sanitize_text_field( wp_unslash( $_POST['customer_name']  ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		$customer_email = sanitize_email(      wp_unslash( $_POST['customer_email'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		$customer_phone = sanitize_text_field( wp_unslash( $_POST['customer_phone'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		$quote_message  = sanitize_textarea_field( wp_unslash( $_POST['quote_message'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$product_id     = isset( $_POST['current_product_id'] ) ? absint( wp_unslash( $_POST['current_product_id'] ) ) : 0;
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$product_name   = isset( $_POST['product_name'] ) ? sanitize_text_field( wp_unslash( $_POST['product_name'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$quantity       = isset( $_POST['quantity'] ) ? max( 1, absint( wp_unslash( $_POST['quantity'] ) ) ) : 1;

		if ( ! $customer_name || ! $customer_email ) {
			wp_send_json_error( array( 'message' => __( 'Please fill in all required fields.', 'wholesalenode-for-woocommerce' ) ) );
		}
		if ( ! is_email( $customer_email ) ) {
			wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'wholesalenode-for-woocommerce' ) ) );
		}

		if ( $product_id && function_exists( 'wc_get_product' ) ) {
			$product = wc_get_product( $product_id );
			if ( $product ) {
				$product_name = $product->get_name();
			}
		}

		$form_data = wp_json_encode( array(
			'customer_name'      => $customer_name,
			'customer_email'     => $customer_email,
			'customer_phone'     => $customer_phone,
			'quote_message'      => $quote_message,
			'current_product_id' => $product_id  ?: null,
			'product_name'       => $product_name ?: null,
			'quantity'           => $quantity,
			'user_id'            => get_current_user_id() ?: null,
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
			'user_ip'            => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
			'form_url'           => isset( $_SERVER['HTTP_REFERER'] ) ? sanitize_url( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '',
		) );

		global $wpdb;
		$table = $wpdb->prefix . 'woowsn_quotes';

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		$wpdb->insert( $table, array(
			'form_data'  => $form_data,
			'status'     => 'pending',
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
			'ip_address' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
			'user_id'    => get_current_user_id() ?: null,
			'created_at' => current_time( 'mysql' ),
			'updated_at' => current_time( 'mysql' ),
		) );

		if ( ! $wpdb->insert_id ) {
			wp_send_json_error( array( 'message' => __( 'Failed to save your request. Please try again.', 'wholesalenode-for-woocommerce' ) ) );
		}

		// Admin email notification.
		$this->notify_admin( $customer_name, $customer_email, $product_name, $quantity, $quote_message );

		wp_send_json_success( array( 'message' => __( 'Your quote request has been submitted. We will be in touch shortly.', 'wholesalenode-for-woocommerce' ) ) );
	}

	/**
	 * Send admin notification for a new quote.
	 *
	 * @param string $name     Customer name.
	 * @param string $email    Customer email.
	 * @param string $product  Product name.
	 * @param int    $quantity Quantity.
	 * @param string $message  Message.
	 */
	private function notify_admin( $name, $email, $product, $quantity, $message ) {
		$settings = $this->settings;
		if ( empty( $settings['send_quote_notifications'] ) ) {
			return;
		}

		$admin_email = $settings['quote_notification_email'] ?: get_option( 'admin_email' );
		$site_name   = get_bloginfo( 'name' );
		$subject     = sprintf(
			/* translators: %s: site name */
			__( '[%s] New B2B Quote Request', 'wholesalenode-for-woocommerce' ),
			$site_name
		);
		$body = sprintf(
			/* translators: 1: customer name, 2: email, 3: product, 4: quantity, 5: message, 6: admin URL */
			__( "A new quote request was submitted.\n\nName: %1\$s\nEmail: %2\$s\nProduct: %3\$s\nQuantity: %4\$d\nMessage: %5\$s\n\nView requests:\n%6\$s", 'wholesalenode-for-woocommerce' ),
			$name, $email, $product, $quantity, $message,
			admin_url( 'admin.php?page=woowsn_free_quote_entries' )
		);

		wp_mail( $admin_email, $subject, $body );
	}
}
