<?php

namespace BWDK\Support;

defined( 'ABSPATH' ) || exit;

class ReturnUrlHelper {
    const SESSION_KEY = 'bwdk_entry_point';

    public static function remember_cart_or_checkout() {
        if ( ! function_exists( 'WC' ) || ! WC()->session ) {
            return;
        }

        if ( function_exists( 'is_cart' ) && is_cart() ) {
            WC()->session->set( self::SESSION_KEY, 'cart' );
        } elseif ( function_exists( 'is_checkout' ) && is_checkout() ) {
            WC()->session->set( self::SESSION_KEY, 'checkout' );
        }
    }

    public static function remember_product( $product_id ) {
        if ( ! function_exists( 'WC' ) || ! WC()->session ) {
            return;
        }

        $product_id = absint( $product_id );
        if ( $product_id > 0 ) {
            WC()->session->set( self::SESSION_KEY, 'product:' . $product_id );
        }
    }

    public static function pop_url() {
        if ( ! function_exists( 'WC' ) || ! WC()->session ) {
            return null;
        }

        $value = WC()->session->get( self::SESSION_KEY );
        if ( null !== $value ) {
            WC()->session->__unset( self::SESSION_KEY );
        }

        if ( 'cart' === $value ) {
            return function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : null;
        }

        if ( 'checkout' === $value ) {
            return function_exists( 'wc_get_checkout_url' ) ? wc_get_checkout_url() : null;
        }

        if ( is_string( $value ) && 0 === strpos( $value, 'product:' ) ) {
            $product_id = (int) substr( $value, 8 );
            if ( $product_id > 0 ) {
                $url = get_permalink( $product_id );
                if ( $url ) {
                    return $url;
                }
            }
        }

        return null;
    }
}














