<?php
/**
 * Form Renderer
 *
 * @package Ugcify\Form
 */

namespace Ugcify\Form;

use Ugcify\Storage\StorageManager;

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

/**
 * Class FormRenderer
 */
class FormRenderer {

	/**
	 * Whether the form is needed on the current page.
	 *
	 * @var bool
	 */
	private $is_form_needed = false;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Mark that the form is needed on the current page.
	 *
	 * @return void
	 */
	public function mark_form_needed() {
		$this->is_form_needed = true;
	}

	/**
	 * Check if the form should be loaded on the current page.
	 *
	 * @return bool
	 */
	private function should_load_form() {
		// If explicitly marked as needed via hook.
		if ( $this->is_form_needed ) {
			return true;
		}

		// Only load on single product pages.
		if ( function_exists( 'is_product' ) && is_product() ) {
			return true;
		}

		// Allow themes/plugins to filter.
		return apply_filters( 'ugcify_load_review_form', false );
	}

	/**
	 * Initialize hooks
	 *
	 * @return void
	 */
	private function init_hooks() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_form_assets' ) );
		add_action( 'wp_footer', array( $this, 'render_modal_container' ) );
		
		// Track if form is needed on current page.
		add_action( 'ugcify_review_form_needed', array( $this, 'mark_form_needed' ) );
	}

	/**
	 * Enqueue form assets
	 *
	 * @return void
	 */
	public function enqueue_form_assets() {
		// Only load assets where the form is needed.
		if ( ! $this->should_load_form() ) {
			return;
		}
		// Enqueue review form script (vanilla JS).
		wp_enqueue_script(
			'ugcify-review-form',
			UGCIFY_URL . 'assets/frontend/review-form.js',
			array(), // No React dependencies!
			UGCIFY_VERSION,
			true
		);

		// Enqueue review form styles.
		wp_enqueue_style(
			'ugcify-review-form',
			UGCIFY_URL . 'assets/frontend/styles.css',
			array(),
			UGCIFY_VERSION
		);

		// Get settings.
		$settings = get_option( 'ugcify_review_form_settings', array(
			'formType'       => 'step-by-step',
			'formVisibility' => 'logged-in',
			'mediaMaxSizeMb' => 10,
			'enableAttachmentLimit' => false,
			'maxAttachmentsPerReview' => 5,
			'maxImageSizeMb' => 10,
			'maxVideoSizeMb' => 50,
		) );

		// Enqueue Google reCAPTCHA if enabled.
		if ( ! empty( $settings['recaptchaEnabled'] ) && ! empty( $settings['recaptchaSiteKey'] ) ) {
			wp_enqueue_script(
				'google-recaptcha',
				'https://www.google.com/recaptcha/api.js',
				array(),
				null, // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
				true
			);
		}

		$current_user = wp_get_current_user();

		// Check if S3 storage is enabled for frontend pre-signed upload flow.
		$storage_manager = new StorageManager();

		// Localize script with settings and data.
		wp_localize_script(
			'ugcify-review-form',
			'ugcReviewForm',
			array(
				'apiUrl'           => rest_url( 'ugcify/v1' ),
				'nonce'            => wp_create_nonce( 'wp_rest' ),
				'pluginUrl'        => UGCIFY_URL,
				'settings'         => $settings,
				'isLoggedIn'       => is_user_logged_in(),
				'currentUser'      => array(
					'id'           => $current_user->ID,
					'name'         => $current_user->display_name,
					'email'        => $current_user->user_email,
				),
				'product'          => $this->get_current_product_data(),
				's3Enabled'        => $storage_manager->is_enabled(),
			)
		);
	}

	/**
	 * Get current product data
	 *
	 * @return array
	 */
	private function get_current_product_data() {
		if ( ! function_exists( 'wc_get_product' ) ) {
			return array();
		}

		global $product; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

		if ( ! $product instanceof \WC_Product ) {
			$product_id = get_the_ID();
			$product    = wc_get_product( $product_id ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
		}

		if ( ! $product instanceof \WC_Product ) {
			return array();
		}

		return array(
			'id'    => $product->get_id(),
			'name'  => $product->get_name(),
			'image' => wp_get_attachment_url( $product->get_image_id() ),
			'sku'   => $product->get_sku(),
		);
	}

	/**
	 * Render modal container in footer
	 *
	 * @return void
	 */
	public function render_modal_container() {
		// Only render modal where the form is needed.
		if ( ! $this->should_load_form() ) {
			return;
		}
		// Get settings.
		$settings = get_option( 'ugcify_review_form_settings', array(
			'formType'       => 'step-by-step',
			'formVisibility' => 'logged-in',
			'mediaMaxSizeMb' => 10,
			'enableAttachmentLimit' => false,
			'maxAttachmentsPerReview' => 5,
			'maxImageSizeMb' => 10,
			'maxVideoSizeMb' => 50,
		) );

		// Get current user data.
		$current_user = wp_get_current_user();
		$user_email   = $current_user->user_email;
		$user_name    = $current_user->display_name;

		// Pass $settings to modal template for conditional rendering.
		$settings = apply_filters( 'ugcify_review_form_settings', $settings );
		include UGCIFY_PATH . 'templates/form/modal.php';
	}

	/**
	 * Render form based on type
	 *
	 * @param array $args Form arguments.
	 * @return string
	 */
	   public function render( $args = array() ) {
		   // Mark form as needed when explicitly rendered (e.g., via shortcode).
		   $this->is_form_needed = true;

		   $defaults = array(
			   'product_id' => get_the_ID(),
			   'type'       => 'button', // 'button', 'inline', 'modal'.
		   );

		   $args = wp_parse_args( $args, $defaults );

		   // Get settings.
		   $settings = get_option( 'ugcify_review_form_settings', array(
			   'formType'       => 'step-by-step',
			   'formVisibility' => 'logged-in',
			   'mediaMaxSizeMb' => 10,
			   'enableAttachmentLimit' => false,
			   'maxAttachmentsPerReview' => 5,
			   'maxImageSizeMb' => 10,
			   'maxVideoSizeMb' => 50,
		   ) );

		   $form_visibility = $settings['formVisibility'];
		   $is_logged_in = is_user_logged_in();
		   $is_verified = false;
		   if ( $is_logged_in && function_exists( 'wc_customer_bought_product' ) ) {
			   $current_user = wp_get_current_user();
			   $is_verified = wc_customer_bought_product( $current_user->user_email, $current_user->ID, $args['product_id'] );
		   }

		   // Who can review logic
		   if ( 'logged-in' === $form_visibility ) {
			   if ( ! $is_logged_in ) {
				   return $this->get_visibility_message( 'logged-in' );
			   }
			   // Only show button/inline for logged-in users
			   if ( 'button' === $args['type'] ) {
				   return $this->render_button( $args );
			   }
			   return $this->render_inline_form( $args );
		   }

		   if ( 'verified-buyers' === $form_visibility ) {
			   if ( ! $is_logged_in ) {
				   return $this->get_visibility_message( 'logged-in' );
			   }
			   if ( ! $is_verified ) {
				   // Show message for not verified
				   return '<div class="ugcify-review-form-message">' . esc_html__( 'Only customers who have purchased this product can write a review. Please purchase the product to submit your review.', 'ugcify' ) . '</div>';
			   }
			   // Only show button/inline for verified buyers
			   if ( 'button' === $args['type'] ) {
				   return $this->render_button( $args );
			   }
			   return $this->render_inline_form( $args );
		   }

		   // Anyone: always show button/inline, never show login message
		   if ( 'button' === $args['type'] ) {
			   return $this->render_button( $args );
		   }
		   return $this->render_inline_form( $args );
	   }

	/**
	 * Render button to open modal
	 *
	 * @param array $args Arguments.
	 * @return string
	 */
	private function render_button( $args ) {
		ob_start();
		?>
		<button 
			type="button"
			class="ugcify-review-form-button" 
			data-product-id="<?php echo esc_attr( $args['product_id'] ); ?>"
		>
			<?php esc_html_e( 'Write a review', 'ugcify' ); ?>
		</button>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render inline form
	 *
	 * @param array $args Arguments.
	 * @return string
	 */
	private function render_inline_form( $args ) {
		ob_start();
		?>
		<div 
			class="ugcify-review-form-inline" 
			data-product-id="<?php echo esc_attr( $args['product_id'] ); ?>"
		></div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Check if user can submit review
	 *
	 * @param string $visibility Form visibility setting.
	 * @param int    $product_id Product ID.
	 * @return bool
	 */
	private function can_user_submit_review( $visibility, $product_id ) {
		switch ( $visibility ) {
			case 'anyone':
				return true;

			case 'logged-in':
				return is_user_logged_in();

			case 'verified-buyers':
				if ( ! is_user_logged_in() ) {
					return false;
				}

				if ( ! function_exists( 'wc_customer_bought_product' ) ) {
					return false;
				}

				$current_user = wp_get_current_user();
				return wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id );

			default:
				return false;
		}
	}

	/**
	 * Get visibility message
	 *
	 * @param string $visibility Visibility setting.
	 * @return string
	 */
	private function get_visibility_message( $visibility ) {
		ob_start();
		?>
		<div class="ugcify-review-form-message">
			<?php
			switch ( $visibility ) {
				case 'logged-in':
					echo wp_kses_post( sprintf(
						/* translators: %1$s: login URL, %2$s: register URL */
						__( 'Please <a href="%1$s">log in</a> or <a href="%2$s">register</a> to write a review.', 'ugcify' ),
						esc_url( wp_login_url( get_permalink() ) ),
						esc_url( wp_registration_url() )
					) );
					break;

				case 'verified-buyers':
					echo esc_html__( 'Only verified buyers can write a review.', 'ugcify' );
					break;

				default:
					echo esc_html__( 'You cannot submit a review at this time.', 'ugcify' );
					break;
			}
			?>
		</div>
		<?php
		return ob_get_clean();
	}
}
