<?php

namespace Pinova\Integrations\Woocommerce;

use Pinova\Helper;
use Pinova\Pinova;

class Redirect {

	public function __construct() {
		add_action( 'template_redirect', [ $this, 'wc_checkout_to_pinova_login' ], 10 );
		add_action( 'woocommerce_get_checkout_url', [ $this, 'wc_checkout_to_pinova_login_url' ], 1000 );
	}

	public function wc_checkout_to_pinova_login() {

		if ( ! is_checkout() || is_user_logged_in() ) {
			return;
		}

		$login_url = Pinova::get_login_url( wc_get_checkout_url() );

		Helper::redirect_to( $login_url );
	}

	public function wc_checkout_to_pinova_login_url( $checkout_url ) {

		if ( is_user_logged_in() ) {
			return $checkout_url;
		}

		$checkout_url = wc_get_page_permalink( 'checkout' );

		if ( is_ssl() || 'yes' === get_option( 'woocommerce_force_ssl_checkout' ) ) {
			$checkout_url = str_replace( 'http:', 'https:', $checkout_url );
		}

		return Pinova::get_login_url( $checkout_url );
	}
}