<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access is not allowed.' );
}

/**
 * Main Wizard Controller Class
 */
class FinalPOS_Wizard {

	/**
	 * Initialize the wizard
	 */
	public static function init() {
		// Register admin post handlers
		add_action( 'admin_post_final_verify_activation_key', array( __CLASS__, 'verify_activation_key_handler' ) );
		add_action( 'admin_post_finalpos_complete_setup', array( __CLASS__, 'complete_setup_handler' ) );
	}

	/**
	 * Render the wizard
	 */
	public static function render() {
		$current_stage = get_option( 'finalpos_current_stage', 'auth_key' );

		// Always force stage to settings if credentials are present
		$jwt_token       = get_option( 'finalpos_jwt_token' );
		$consumer_key    = get_option( 'finalpos_consumer_key' );
		$consumer_secret = get_option( 'finalpos_consumer_secret' );

		// If we have all credentials and we're not at the settings stage, update it
		if ( $jwt_token && $consumer_key && $consumer_secret && $current_stage !== 'settings' ) {
			$current_stage = 'settings';
			update_option( 'finalpos_current_stage', 'settings' );
		}

		// Check if there's a stage parameter in the URL.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Stage parameter controls navigation; sensitive operations use custom nonce below.
		if ( isset( $_GET['stage'] ) && in_array( sanitize_text_field( wp_unslash( $_GET['stage'] ) ), array( 'auth_key', 'settings' ), true ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$requested_stage = sanitize_text_field( wp_unslash( $_GET['stage'] ) );

			// Only allow moving to settings if we have required data.
			if ( $requested_stage === 'settings' ) {
				// If this is a redirect from WooCommerce auth with nonce, verify it.
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Custom nonce verification follows.
				if ( isset( $_GET['finalpos_nonce'] ) ) {
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
					$nonce          = sanitize_text_field( wp_unslash( $_GET['finalpos_nonce'] ) );
					$transient_name = 'finalpos_auth_nonce_' . $nonce;

					// Verify nonce is valid - with fallback to option
					$valid_nonce = false;

					// Check transient first
					if ( get_transient( $transient_name ) === 'valid' ) {
						$valid_nonce = true;
					}
					// Fallback to option storage if transient failed
					else {
						$last_nonce      = get_option( 'finalpos_last_nonce', '' );
						$last_nonce_time = get_option( 'finalpos_last_nonce_time', 0 );
						$one_hour_ago    = time() - 3600;

						// Verify nonce matches and was created less than an hour ago
						if ( $nonce === $last_nonce && $last_nonce_time > $one_hour_ago ) {
							$valid_nonce = true;
						}
					}

					if ( ! $valid_nonce ) {
						// Nonce verification failed - don't update stage and show auth form
						$current_stage = 'auth_key';
						update_option( 'finalpos_current_stage', 'auth_key' );

						// Display error message via transient (to be shown in the form)
						set_transient( 'finalpos_setup_error', 'Security verification failed. Please try again.', 60 );

						// Continue to render function with auth_key stage
					} else {
						// Valid nonce, clean it up
						delete_transient( $transient_name );

						// Only proceed if we have all required credentials
						if ( $jwt_token && $consumer_key && $consumer_secret ) {
							$current_stage = 'settings';
							update_option( 'finalpos_current_stage', 'settings' );
						}
					}
				} else {
					// Normal non-WooCommerce redirect to settings
					if ( $jwt_token && $consumer_key && $consumer_secret ) {
						$current_stage = 'settings';
						update_option( 'finalpos_current_stage', 'settings' );
					}
				}
			} elseif ( $requested_stage === 'auth_key' ) {
				// For auth_key stage, just update
				$current_stage = $requested_stage;
				update_option( 'finalpos_current_stage', $requested_stage );
			}
		}
		?>
		<div class="finalpos-wrap finalpos-wizard">
			<div class="finalpos-logo">
				<img src="<?php echo FINALPOS_PLUGIN_URL; ?>assets/img/final-logo.svg" alt="Final POS Logo">
			</div>
				<?php
				switch ( $current_stage ) {
					case 'auth_key':
						self::render_activation_form();
						break;
					case 'settings':
						self::render_settings_form();
						break;
					default:
						update_option( 'finalpos_current_stage', 'auth_key' );
						self::render_activation_form();
						break;
				}
				?>
		</div>
		<?php
	}

	/**
	 * Render activation form
	 */
	public static function render_activation_form() {
		require_once FINALPOS_PLUGIN_DIR . 'includes/admin/wizard/views/activation-form.php';
	}

	/**
	 * Render settings form
	 */
	public static function render_settings_form() {
		require_once FINALPOS_PLUGIN_DIR . 'includes/admin/wizard/views/settings-form.php';
	}

	/**
	 * Handler for the activation key verification
	 */
	public static function verify_activation_key_handler() {
		check_admin_referer( 'final_activation_action', 'final_activation_nonce' );
		$activation_key = isset( $_POST['activation_key'] ) ? sanitize_text_field( $_POST['activation_key'] ) : '';
		$redirect_url   = admin_url( 'admin.php?page=finalpos-setup' );

		if ( empty( $activation_key ) ) {
			wp_redirect( add_query_arg( 'error', urlencode( 'Please enter an activation key.' ), $redirect_url ) );
			exit;
		}

		$endpoint = 'v1/api/woo-auth/validate/' . $activation_key;
		$headers  = array( 'Content-Type' => 'application/json' );

		$response = FinalPOS_Common::api_request( $endpoint, 'GET', null, $headers );

		if ( is_wp_error( $response ) ) {
			FinalPOS_Common::handle_api_error(
				$response,
				$redirect_url,
				'Activation request failed',
				array( 'endpoint' => $endpoint )
			);
		}

		if ( ! $response['success'] ) {
			if ( is_array( $response['body'] ) ) {
				if ( empty( $response['body']['success'] ) && ! isset( $response['body']['token'] ) ) {
					$message = isset( $response['body']['message'] ) ? $response['body']['message'] : 'Activation failed.';
					wp_redirect( add_query_arg( 'error', urlencode( $message ), $redirect_url ) );
					exit;
				}
			} elseif ( trim( $response['body'] ) !== 'Sync Started' && trim( $response['body'] ) !== 'Activation Successful' ) {
					wp_redirect( add_query_arg( 'error', urlencode( 'Activation failed.' ), $redirect_url ) );
					exit;
			}
		}

		// Check if we have a token in the response
		$jwt_token = '';
		if ( is_array( $response['body'] ) && isset( $response['body']['token'] ) ) {
			$jwt_token = $response['body']['token'];
		} else {
			wp_redirect( add_query_arg( 'error', urlencode( 'No JWT token received from activation.' ), $redirect_url ) );
			exit;
		}

		// Validate and save the JWT token
		if ( empty( $jwt_token ) ) {
			wp_redirect( add_query_arg( 'error', urlencode( 'Invalid JWT token received.' ), $redirect_url ) );
			exit;
		}

		// Use our helper function to update and validate the token
		if ( ! FinalPOS_Common::update_jwt_token( $jwt_token ) ) {
			wp_redirect( add_query_arg( 'error', urlencode( 'Invalid JWT token received.' ), $redirect_url ) );
			exit;
		}

		// Generate WooCommerce auth URL for the redirect
		$wc_auth_url = self::generate_wc_auth_url();

		// Show success page with redirect
		self::render_success_and_redirect( $wc_auth_url );
		exit;
	}

	/**
	 * Generate WooCommerce auth URL
	 *
	 * @return string The WooCommerce auth URL
	 */
	private static function generate_wc_auth_url() {
		// Generate nonce - unique value based on current time and random value
		$nonce = wp_generate_password( 12, false );

		// Store nonce in a transient with longer expiration (1 hour)
		$transient_name = 'finalpos_auth_nonce_' . $nonce;
		set_transient( $transient_name, 'valid', 3600 );

		// Also store in an option as backup (in case transients are unreliable)
		update_option( 'finalpos_last_nonce', $nonce, false );
		update_option( 'finalpos_last_nonce_time', time(), false );

		// Set up callback and return URLs - Use WC-AJAX endpoint
		$callback_url = add_query_arg(
			array(
				'wc-ajax'        => 'finalpos_save_token',
				'finalpos_nonce' => $nonce,
			),
			home_url( '/' )
		);

		// Build the return URL - make sure to include page parameter first, then stage
		$return_url = add_query_arg(
			array(
				'page'           => 'finalpos-setup',
				'stage'          => 'settings',
				'finalpos_nonce' => $nonce,
			),
			admin_url( 'admin.php' )
		);

		// Setup auth parameters
		$auth_params = array(
			'app_name'     => 'FinalPOS',
			'scope'        => 'read_write',
			'user_id'      => get_current_user_id(),
			'return_url'   => $return_url,
			'callback_url' => $callback_url,
		);

		// Generate the auth URL
		$wc_auth_url = home_url( 'wc-auth/v1/authorize' ) . '?' . http_build_query( $auth_params );

		return $wc_auth_url;
	}

	/**
	 * Render success page and handle redirection
	 *
	 * @param string $redirect_url URL to redirect to
	 */
	private static function render_success_and_redirect( $redirect_url ) {
		?>
		<!DOCTYPE html>
		<html>
		<head>
			<meta charset="UTF-8">
			<meta name="viewport" content="width=device-width, initial-scale=1.0">
			<title><?php esc_html_e( 'Final POS - Connecting...', 'finalpos' ); ?></title>
			<link rel="stylesheet" href="<?php echo FINALPOS_PLUGIN_URL; ?>assets/css/finalpos-loader.css">
		</head>
		<body class="finalpos-loader-screen">
			<div class="finalpos-loader-container">
				<div class="finalpos-loader-logo">
					<img src="<?php echo FINALPOS_PLUGIN_URL; ?>assets/img/final-logo.svg" alt="Final POS Logo">
				</div>
				<div class="finalpos-loader-success">
					<?php esc_html_e( 'Activation successful!', 'finalpos' ); ?>
				</div>
				<div class="finalpos-loader-message">
					<?php esc_html_e( 'Connecting to your WooCommerce store...', 'finalpos' ); ?>
				</div>
				<div class="finalpos-loader-progress">
					<div class="finalpos-loader-progress-bar"></div>
				</div>
			</div>
			<script>
				setTimeout(function() {
					window.location.href = "<?php echo esc_url_raw( $redirect_url ); ?>";
				}, 1000);
			</script>
		</body>
		</html>
		<?php
	}

	/**
	 * Handler for completing the setup
	 */
	public static function complete_setup_handler() {
		check_admin_referer( 'final_settings_action', 'final_settings_nonce' );
		$redirect_url = admin_url( 'admin.php?page=finalpos-setup' );

		$jwt_token = get_option( 'finalpos_jwt_token' );
		if ( empty( $jwt_token ) ) {
			wp_redirect( add_query_arg( 'error', urlencode( 'JWT token missing' ), $redirect_url ) );
			exit;
		}

		$consumer_key    = get_option( 'finalpos_consumer_key' );
		$consumer_secret = get_option( 'finalpos_consumer_secret' );
		$site_url        = trailingslashit( home_url() );
		$terms           = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => false,
			)
		);
		$categories      = ! is_wp_error( $terms ) ? wp_list_pluck( $terms, 'term_id' ) : array();
		$company_id      = FinalPOS_Common::get_parsed_jwt_data( 'company' )['id'] ?? '';

		if ( empty( $company_id ) ) {
			wp_redirect( add_query_arg( 'error', urlencode( 'Company ID not set' ), $redirect_url ) );
			exit;
		}

		// Get sync settings from form
		$products_sync_enabled    = isset( $_POST['products_sync_enabled'] ) ? (int) $_POST['products_sync_enabled'] : 1;
		$products_sync_from_date  = isset( $_POST['products_sync_from_date'] ) ? sanitize_text_field( $_POST['products_sync_from_date'] ) : '';
		$products_sync_categories = isset( $_POST['products_sync_categories'] ) ? sanitize_text_field( $_POST['products_sync_categories'] ) : '';

		$orders_sync_enabled   = isset( $_POST['orders_sync_enabled'] ) ? (int) $_POST['orders_sync_enabled'] : 1;
		$orders_sync_from_date = isset( $_POST['orders_sync_from_date'] ) ? sanitize_text_field( $_POST['orders_sync_from_date'] ) : '';

		$customers_sync_enabled = isset( $_POST['customers_sync_enabled'] ) ? (int) $_POST['customers_sync_enabled'] : 1;

		// Format dates for API
		$products_from_date  = date( 'Y-m-d\TH:i:s.000+00:00', strtotime( $products_sync_from_date ) );
		$orders_from_date    = date( 'Y-m-d\TH:i:s.000+00:00', strtotime( $orders_sync_from_date ) );
		$customers_from_date = '2000-01-01T00:00:00.000+00:00'; // Default value for customers - not in use

		// Parse product categories if provided
		$product_categories = array();
		if ( ! empty( $products_sync_categories ) ) {
			$product_categories = json_decode( stripslashes( $products_sync_categories ), true );
			if ( json_last_error() !== JSON_ERROR_NONE ) {
				$product_categories = $categories; // Fallback to all categories if JSON parsing fails
			}
		} else {
			$product_categories = $categories; // Use all categories if none specified
		}

		$data = array(
			'apiCredentials' => array(
				'url'      => $site_url,
				'key'      => $consumer_key,
				'secret'   => $consumer_secret,
				'platform' => 'woo-commerce',
			),
			'syncSettings'   => array(
				'orderSyncSettings'    => array(
					'fromDate'   => $orders_from_date,
					'shouldSync' => $orders_sync_enabled === 1 ? true : false,
				),
				'productSyncSettings'  => array(
					'fromDate'   => $products_from_date,
					'shouldSync' => $products_sync_enabled === 1 ? true : false,
					'categories' => $product_categories,
				),
				'customerSyncSettings' => array(
					'fromDate'   => $customers_from_date,
					'shouldSync' => $customers_sync_enabled === 1 ? true : false,
				),
			),
		);

		$endpoint = "v1/api/woo-sync/$company_id";
		$headers  = FinalPOS_Common::get_auth_headers();

		$response = FinalPOS_Common::api_request( $endpoint, 'PUT', $data, $headers );

		FinalPOS_Common::handle_api_error( $response, $redirect_url, 'Setup failed' );

		// If we reach here, the request was successful
		update_option( 'finalpos_current_stage', 'complete' );
		wp_redirect( add_query_arg( 'message', urlencode( 'Setup complete.' ), $redirect_url ) );
		exit;
	}
}